我试图了解当您同时拥有 props
时会发生什么和 useState
在一个组件中。
我写了一个小例子,它有一个父组件用另一个子组件打印它的数字 -
const MyNumbers = (props) => {
const [numbers, setNumbers] = useState([...props.arr]);
function changeNumbers() {
setNumbers((nums) => [...nums.map(() => Math.floor(Math.random() * 10))]);
}
return (
<div className="MyNumbers">
<div>
<button onClick={changeNumbers}>Chane numbers</button>
</div>
<div>
{numbers.map((num, idx) => (
<SingleNumber key={idx} num={num}></SingleNumber>
))}
</div>
</div>
);
};
const SingleNumber = (props) => {
const [num] = useState(props.num);
useEffect(() => {
console.log("useEffect called");
});
return <h3>The number is {num}</h3>;
};
Here is the above demoSingleNumber
组件使用 useState
如您所见,单击“更改数字”操作不会更改子组件中的值。但是当我写几乎相同的代码但现在
SingleNumber
不使用 useState
然后单击“更改数字”会更改子组件(like in this demo)中的所有值。使用
useState
的功能组件是否正确?渲染一次,然后仅在状态更改时才更改,但如果 props
则不会更改改变了?
最佳答案
当 Prop 改变时,OFC 组件“重新渲染”,useEffect
Hook SingleNumber
是 显示 您认为每次 Prop 更改时都会运行“渲染阶段”......每次渲染组件时都会运行效果。
const SingleNumber = (props) => {
const [num] = useState(props.num);
useEffect(() => {
console.log("useEffect called"); // <-- logged each time the component renders
});
return <h3>The number is {num}</h3>;
};
如果您添加了对 props.num
的依赖项并更新本地状态(实际上不要这样做,这是 react 中的反模式!),每次 Prop 更新时,您都会看到 UI 再次更新。要回答您的问题:
Is it correct to say that a function component with a
useState
renders once and then only changed if the state changed but not if theprops
changed?
不,这在技术上是不正确的,如果“渲染”对您意味着严格 react 渲染组件以计算差异, react 组件在状态或 Prop 更新时重新渲染。是的,如果“渲染”更普遍地意味着您可以直观地看到 UI 更新。
关于javascript - useState 和 props 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65336835/