【问题标题】:Logical error in React useEffect and conditional statementReact useEffect 和条件语句中的逻辑错误
【发布时间】:2021-01-04 17:06:24
【问题描述】:

我最近问了一个关于 React 中 useState 导致的无限循环的问题,我得到了帮助。但是现在我有另一个相同代码的错误;

const [scoutMode, setScoutMode] = useState("");
const [bottomLinks, setBottomLinks] = useState([]);

useEffect(() => {

setScoutMode("weeklyProgramme");

if (scoutMode == "weeklyProgramme") {
  setBottomLinks(["x", "y"])
  console.log("weeklyprogramme");

} 
else if (scoutMode == "camp") {
  setBottomLinks(["a", "b"])
  console.log("camp");

} 

else {
  setBottomLinks(["c", "d"]);
  console.log("None")
}
console.log(bottomLinks);
}, [scoutMode])

我希望它在控制台中写入 ["x", "y"] 和 "weeklyprogramme",因为显然第一个条件为真,但输出却是这样的: picture of output

看起来它部分运行第一个条件的语句和 else 语句。有人可以解释一下吗? React 或 hook 是否会意外工作?

【问题讨论】:

    标签: reactjs if-statement react-hooks use-state


    【解决方案1】:

    setBottomLinks() 是异步方法,因此您无法在setBottomLinks() 之后立即获取bottomLinks 的更新值。

        setBottomLinks(...)
        console.log(bottomLinks) // This will console old value of bottomLinks
    

    您应该使用 useEffect 并添加 bottomLinks 依赖项来检查更新的状态值。

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

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 1970-01-01
      • 2021-10-24
      • 2020-03-22
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 2021-12-08
      • 2011-07-19
      相关资源
      最近更新 更多