【问题标题】:Increment value in useEffect() in ReactJSReactJS 中 useEffect() 中的增量值
【发布时间】:2020-12-01 17:37:42
【问题描述】:

我正在开发我的第一个 ReactJS 应用程序。在下面的代码中,count 的值在第二个 Axios post 方法中没有改变-

export default function Dashboard(props){
   const [count, setCount] = useState(0);

   useEffect(()=>{
    let postData = new FormData();
    postData.append("eiin", eiinNo);
    Axios.post("url",postData).then(response=>{
        if(response.data){     
        }
    }).catch(error=>{
        console.log(error);
    });


    Axios.post("another-url", postData).then(response=>{
        const items = response.data;
        items.map(item=>{
            setCount(count => count + 1);
            console.log(count); //count remains 0, but 2 items here.               
        })
    }).catch(error=>{
        console.log(error);
    });

  },[]);
}

我在这里做错了什么?

【问题讨论】:

  • 您的 axios 帖子“another-url”似乎没有检索到任何数据,这就是计数器没有增加的原因
  • @zS1L3NT 有一些数据。
  • 我希望 setCount 在重新渲染发生之前不会生效。
  • 状态更新是异步的,你不能在“setState”之后console.log 并期望看到更新的值。
  • setCount 是异步的,因此在下一行可能不会更新。如果要使用 count 的更新值,请添加 useEffectcount 作为依赖项

标签: reactjs use-effect use-state


【解决方案1】:

正如 cmets 所提到的,这里的 setCount 函数将对组件状态的更新进行排队,这样当组件下次渲染时,它就会有一个带有新值的计数。它还会在稍后使用可用的新计数值触发组件的重新渲染。

在这段代码中:

        items.map(item=>{
            setCount(count => count + 1);
            console.log(count); //count remains 0, but 2 items here.               
        })

计数值还没有改变,因为 setCount 稍后才会应用。

如果您将console.log(count) 放在const [count, setCount] = useState(0); 之后,您应该会看到计数正在更新。

另外(我认为)多次调用 setCount 可能并不理想,尽管(我认为)react 会将所有这些更新排队并在重新渲染之前一次运行它们,但使用你希望它改变的数量。

【讨论】:

  • 因为 setCount 是异步的,所以计数只会在重新渲染时更新(它会触发)。如果您在const [count, setCount] = useState(0); 之后放置一个console.log(count),您应该会看到count 得到更新。 (您的示例也是如此。)
  • 我的情况应该是什么解决方案?
  • 这取决于你想要做什么。如果您想在 map 函数中使用新的计数,那么我的猜测是您应该能够使用 local_count 变量,就像我以前版本的这个答案一样。
【解决方案2】:

正如我在上面的评论中提到的,setCount 是异步的,所以在下一行它可能不会更新。如果要使用 count 的更新值,请添加 useEffectcount 作为依赖项。

如下所示:

useEffect(() => {
  console.log(count); // here you should get the updated value of count
}, [count])

这是example sandbox

【讨论】:

  • 这会创建一个无限循环,我的浏览器会挂起。
  • @s.k.paul 你检查示例沙箱了吗?它不会在那里无限循环
  • 因为这里没有增加计数。
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 2022-12-19
  • 2021-12-18
  • 2021-05-05
  • 2020-07-24
  • 2021-10-12
  • 2021-02-16
  • 1970-01-01
相关资源
最近更新 更多