【发布时间】:2022-07-09 19:49:22
【问题描述】:
我在问是否有(如果有,什么是)推荐的方法来使用来自 props 的值初始化 React 挂钩中的状态变量。
所以我假设我有一个这样的组件:
function SomeComponent(props) {
return (
....
);
}
我可以使用useState为这个组件创建一个变量,像这样:
const [someVariable, setSomeVariable] = useState('someValue');
到目前为止一切顺利。 我现在的问题是,如果我想用 props 中的值初始化变量,是否建议直接这样:
function SomeComponent(props) {
const [someVariable, setSomeVariable] = useState(props.someValue);
}
或者最好用null初始化它,然后用useEffect()在加载时设置值:
function SomeComponent(props) {
const [someVariable, setSomeVariable] = useState(null);
useEffect(() => {
setSomeVariable(props.someValue);
},[])
}
也许还有更多方法。我只是想知道这里是否有建议,或者最终您使用哪种方式并不重要。
【问题讨论】:
-
sameValue 多久更改一次?
-
嗯,好的。感谢您的评论。这也应该被考虑。谢谢!
标签: reactjs react-hooks