使用 useContext 时状态不更新

发布于 2025-01-10 01:18:38 字数 3661 浏览 1 评论 0原文

我正在学习如何使用Context。我单击了一个按钮来更新我的状态,但是当我尝试在另一个组件上使用 useContext 时,它似乎没有更新该状态。我可以看到我的卡组件上的状态更新。当我在上下文中控制台记录测试时,它不会显示传递给它的任何状态。我将状态从卡组件传递到 cardContext 中,以便我可以在其他地方使用

卡组件设置状态

import { useState, useEffect } from 'react';
import { Button } from 'react-bootstrap';

import './Card.css';

function Card() {
    const API_KEY = '';
    const BASE_URL = ``;

    const [coins, setCoins] = useState([]);
   
    const [tests, setTests] = useState('');

    // console.log(coinsSelected);
    console.log(tests);

    const getPrice = async () => {
        const updatedPrice = await axios.get(BASE_URL);
        setCoins(updatedPrice.data);
    };

    useEffect(() => {
        getPrice();
    }, []);

    return (
        <div className="card-container">
            {coins.map((coin) => (
                <div className="card" key={coin.id}>
                    <div className="flip-card">
                        <div className="flip-card-inner">
                            <div className="flip-card-front">
                                {coin.logo_url === '' ? (
                                    <h1>No Image</h1>
                                ) : (
                                    <img src={coin.logo_url} alt="coin"></img>
                                )}
                                <div className="flip-card-price">
                                    <h3>{coin.name}</h3>

                                    <p>{coin.price}</p>
                                </div>
                            </div>

                            <div className="flip-card-back">
                                <h3>ATH -{coin.high}</h3>
                            </div>
                        </div>
                    </div>
                    <div className="card__button">
                        <Button
                            variant="primary"
                            
                            onClick={(e) => setTests(e.currentTarget.value)}
                            value={coin.id}
                        >
                            Buy
                        </Button>
                    </div>
                </div>
            ))}
        </div>
    );
}
export default Card;

CardContext


export const CardContext = createContext();

export const CardProvider = (props) => {
    const [coinsSelected, setCoinsSelected] = useState([]);
    const [tests, setTests] = useState('');

    return (
        <CardContext.Provider value={[tests, setTests]}>
            {props.children}
        </CardContext.Provider>
    );
};

尝试在此处使用


import { CardContext } from '../../Context/CardContext';

function Swap() {
    const [tests, setTests] = useContext(CardContext);

    console.log('foo', tests);

    return (
        <div>
            <h1>{tests}</h1>
        </div>
    );
}
export default Swap;

上下文示例数据

    "id": "BNB",
    "currency": "BNB",
    "symbol": "BNB",
    "name": "Binance Coin",
    "logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/bnb.svg",
    "status": "active",
    "platform_currency": "BNB",
    "price": "362.89854083",
    "price_date": "2022-02-25T00:00:00Z",
    "price_timestamp": "2022-02-25T05:49:00Z",
    "circulating_supply": "168137036",
    "max_supply": "168137036",
    "market_cap": "61016684987"
}```

I am learning how to useContext. I have a button click that is updating my state but when I try to useContext on another component it doesnt seem to be updating that state. I can see the state updating on my card component. When I consolelog the test in my Context it doesn't show any state passed to it. I am passing the state from the card component into the cardContext so I can use elsewhere

Card Component setting state

import { useState, useEffect } from 'react';
import { Button } from 'react-bootstrap';

import './Card.css';

function Card() {
    const API_KEY = '';
    const BASE_URL = ``;

    const [coins, setCoins] = useState([]);
   
    const [tests, setTests] = useState('');

    // console.log(coinsSelected);
    console.log(tests);

    const getPrice = async () => {
        const updatedPrice = await axios.get(BASE_URL);
        setCoins(updatedPrice.data);
    };

    useEffect(() => {
        getPrice();
    }, []);

    return (
        <div className="card-container">
            {coins.map((coin) => (
                <div className="card" key={coin.id}>
                    <div className="flip-card">
                        <div className="flip-card-inner">
                            <div className="flip-card-front">
                                {coin.logo_url === '' ? (
                                    <h1>No Image</h1>
                                ) : (
                                    <img src={coin.logo_url} alt="coin"></img>
                                )}
                                <div className="flip-card-price">
                                    <h3>{coin.name}</h3>

                                    <p>{coin.price}</p>
                                </div>
                            </div>

                            <div className="flip-card-back">
                                <h3>ATH -{coin.high}</h3>
                            </div>
                        </div>
                    </div>
                    <div className="card__button">
                        <Button
                            variant="primary"
                            
                            onClick={(e) => setTests(e.currentTarget.value)}
                            value={coin.id}
                        >
                            Buy
                        </Button>
                    </div>
                </div>
            ))}
        </div>
    );
}
export default Card;

CardContext


export const CardContext = createContext();

export const CardProvider = (props) => {
    const [coinsSelected, setCoinsSelected] = useState([]);
    const [tests, setTests] = useState('');

    return (
        <CardContext.Provider value={[tests, setTests]}>
            {props.children}
        </CardContext.Provider>
    );
};

Trying to use Context here


import { CardContext } from '../../Context/CardContext';

function Swap() {
    const [tests, setTests] = useContext(CardContext);

    console.log('foo', tests);

    return (
        <div>
            <h1>{tests}</h1>
        </div>
    );
}
export default Swap;

Sample Data

    "id": "BNB",
    "currency": "BNB",
    "symbol": "BNB",
    "name": "Binance Coin",
    "logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/bnb.svg",
    "status": "active",
    "platform_currency": "BNB",
    "price": "362.89854083",
    "price_date": "2022-02-25T00:00:00Z",
    "price_timestamp": "2022-02-25T05:49:00Z",
    "circulating_supply": "168137036",
    "max_supply": "168137036",
    "market_cap": "61016684987"
}```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜扑 2025-01-17 01:18:38

为了让 Card 组件访问 CardContext 值,它必须在 CardProvider 创建的子树中呈现。然后它可以解构并访问 testssetTests 上下文值。

示例:

const CardContext = createContext(["", () => {}]);

const CardProvider = (props) => {
  const [coinsSelected, setCoinsSelected] = useState([]);
  const [tests, setTests] = useState("");

  return (
    <CardContext.Provider value={[tests, setTests]}>
      {props.children}
    </CardContext.Provider>
  );
};

...

function App() {
  return (
    <div className="App">
      <CardProvider>
        <Card />
      </CardProvider>
    </div>
  );
}

...

function Card() {
  const API_KEY = "";
  const BASE_URL = ``;

  const [coins, setCoins] = useState([]);

  const [tests, setTests] = useContext(CardContext); // <-- access context value

  console.log(tests);

  const getPrice = async () => {
    const updatedPrice = await axios.get(BASE_URL);
    setCoins(updatedPrice.data);
  };

  useEffect(() => {
    getPrice();
  }, []);

  return (
    <div className="card-container">
      {coins.map((coin) => (
        <div className="card" key={coin.id}>
          <div className="flip-card">
            <div className="flip-card-inner">
              <div className="flip-card-front">
                {coin.logo_url === "" ? (
                  <h1>No Image</h1>
                ) : (
                  <img src={coin.logo_url} alt="coin" height={100} />
                )}
                <div className="flip-card-price">
                  <h3>{coin.name}</h3>

                  <p>{coin.price}</p>
                </div>
              </div>

              <div className="flip-card-back">
                <h3>ATH -{coin.high}</h3>
              </div>
            </div>
          </div>
          <div className="card__button">
            <Button
              variant="primary"
              onClick={(e) => setTests(coin.id)}
            >
              Buy
            </Button>
          </div>
        </div>
      ))}
    </div>
  );
}

编辑状态-not-updating-when-using-usecontext

In order for the Card component to access the CardContext value it must be rendered in the subtree created by CardProvider. It can then destructure and access the tests and setTests context values.

Example:

const CardContext = createContext(["", () => {}]);

const CardProvider = (props) => {
  const [coinsSelected, setCoinsSelected] = useState([]);
  const [tests, setTests] = useState("");

  return (
    <CardContext.Provider value={[tests, setTests]}>
      {props.children}
    </CardContext.Provider>
  );
};

...

function App() {
  return (
    <div className="App">
      <CardProvider>
        <Card />
      </CardProvider>
    </div>
  );
}

...

function Card() {
  const API_KEY = "";
  const BASE_URL = ``;

  const [coins, setCoins] = useState([]);

  const [tests, setTests] = useContext(CardContext); // <-- access context value

  console.log(tests);

  const getPrice = async () => {
    const updatedPrice = await axios.get(BASE_URL);
    setCoins(updatedPrice.data);
  };

  useEffect(() => {
    getPrice();
  }, []);

  return (
    <div className="card-container">
      {coins.map((coin) => (
        <div className="card" key={coin.id}>
          <div className="flip-card">
            <div className="flip-card-inner">
              <div className="flip-card-front">
                {coin.logo_url === "" ? (
                  <h1>No Image</h1>
                ) : (
                  <img src={coin.logo_url} alt="coin" height={100} />
                )}
                <div className="flip-card-price">
                  <h3>{coin.name}</h3>

                  <p>{coin.price}</p>
                </div>
              </div>

              <div className="flip-card-back">
                <h3>ATH -{coin.high}</h3>
              </div>
            </div>
          </div>
          <div className="card__button">
            <Button
              variant="primary"
              onClick={(e) => setTests(coin.id)}
            >
              Buy
            </Button>
          </div>
        </div>
      ))}
    </div>
  );
}

Edit state-not-updating-when-using-usecontext

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文