React.useState 不会从 props 重新加载状态 [英] React.useState does not reload state from props
本文介绍了React.useState 不会从 props 重新加载状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望状态在 props 更改时重新加载,但这不起作用并且 user
变量在下一次 useState
调用时没有更新,有什么问题?>
I'm expecting state to reload on props change, but this does not work and user
variable is not updated on next useState
call, what is wrong?
function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}
推荐答案
传递给 useState 的参数是初始状态,很像在类组件的构造函数中设置状态,不用于在重新渲染时更新状态
The argument passed to useState is the initial state much like setting state in constructor for a class component and isn't used to update the state on re-render
如果你想在 prop 改变时更新状态,使用 useEffect
钩子
If you want to update state on prop change, make use of useEffect
hook
function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
React.useEffect(() => {
setUser(props.user);
}, [props.user])
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}
这篇关于React.useState 不会从 props 重新加载状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文