之后如何立即参考useState设置的值?

时间:2019-11-16 08:41:26

标签: javascript reactjs react-hooks

连续React.useState()设置器不起作用。

const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);

React.useEffect(() => {
  console.log('first use Effect');
  getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
  .then(result => {
    console.log(result); // [{...},{...},・・・,{...}]

    setCampaigns(result);

    console.log(campaigns); // [] this is problem part
  });
}, []);

此后如何立即参考useState设置的值?

3 个答案:

答案 0 :(得分:3)

您必须使用为其设置的值,直到下一次刷新组件为止,因为状态仅在重新渲染时更新

答案 1 :(得分:2)

您需要在单独的useEffect中对其进行跟踪,并在其中接收更新后的值:

useEffect(() => {
  console.log(campaigns);
}, [campaigns])

另一种选择是使用在状态上设置的值,而不是实际的状态值:

React.useEffect(() => {
  console.log('first use Effect');
  getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
  .then(result => {
    console.log(result); // [{...},{...},・・・,{...}]

    setCampaigns(result);

    console.log(result); // Access the result here, which is the same as campaigns
  });
}, []);

答案 2 :(得分:-1)

实际上它可以正常工作,因为setCampaigns可以异步运行,因此您无法在控制台中看到广告系列。

const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);

React.useEffect(() => {
  console.log('first use Effect');
  getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
  .then(result => {
    console.log(result); // [{...},{...},・・・,{...}]

    setCampaigns(result);//this function works

    console.log(campaigns); // but setCampaigns function works async
  });
}, []);

如果要立即访问它,则需要编写以下代码,这意味着更改广告系列对象会自动触发useeffect函数

   React.useEffect(() => {         
        console.log(campaigns); // you can see your state data
      });
    }, [campaigns]);