简体   繁体   English

React.js useState 值不异步匹配

[英]React.js useState values do not match asynchronously

I'm having an odd issue where some times the value passed into useState is not the same as the variable for useState .我有一个奇怪的问题,有时传递给useState的值与useState的变量useState This happens on the same UI component each time while others are not having the issue.每次都在同一个 UI 组件上发生这种情况,而其他组件则没有问题。 Just wanted to double check if I'm doing anything wrong here.只是想仔细检查一下我是否在这里做错了什么。

// userData is from Redux store
const {userData} = props 

const [installed, setInstalled] = useState(userData.installed)  // installed: boolean

console.log(userData.installed) // returns true
console.log(installed) // returns false
console.log(userData) // installed: true

Reason I'm using useState is because I'm using it to render a button that will be toggled, as well as displaying an indicator whether it is toggled or not.我使用 useState 的原因是因为我使用它来呈现一个将被切换的按钮,以及显示一个指示符是否被切换。

<Button onClick={() => setInstalled(!installed) />

I recommend to use useEffect to watch the state inside your Redux store then update the local state based on that changes :我建议使用useEffect来观察 Redux 存储中的状态,然后根据该更改更新本地状态:

const [userData] = props ;
const [installed, setInstalled] = useState(userData.installed)

useEffect(() => {
  setInstalled(userData.installed)
},[userData])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM