gpt4 book ai didi

javascript - React是否保证 `props`对象引用保持稳定?

转载 作者:行者123 更新时间:2023-12-04 00:05:31 24 4
gpt4 key购买 nike

最近,我看到了类似于以下虚构示例的代码:

const MyComp = props => {
const [prevProps, setPrevProps] = useState(props)

if (props !== prevProps) {
setPrevProps(props);
// do something else...
}
}

该组件使用某种派生状态来记住以前的 Prop 。如果 props的存储位置已更改( props !== prevProps),它将把新 Prop 同步到 useState

是的,这没有多大意义,但是我的意思是:React是否可以做出任何保证,因为 props的包含属性没有更改,所以 props的对象引用保持不变?

至少,我所做的测试似乎是这种情况。如果父组件更改了任何 Prop ,则将创建一个新的 props对象。

我将不胜感激任何证明这一点的官方文档链接。

最佳答案

Does React make any guarantees, that the object reference of props stays the same, given no contained property of props has changed?



不,不是。

If a parent component changes any of the props, there will be a new props object created.



如果 parent 重新渲染了 ,则 child 将始终在新对象中接收其 Prop ,即使其中没​​有任何变化。

如果要防止这种情况,则必须使用 PureComponent React.memo 将对 props对象的所有属性进行浅等的比较,并在没有更改任何属性的情况下防止重新呈现。

const { memo, useState, useEffect } = React;

const Child = props => {
// only gets called when `props` changes
useEffect(() => console.log(props.name, ": props changed"), [props]);

return <p>{props.name}: {props.text}</p>;
};

const MemoChild = memo(Child);

const Parent = () => {
const [count, setCount] = useState(0);
const [text, setText] = useState("foo");
const handleTextChange = event => setText(event.target.value);

return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Click to force Re-Render
</button>
<input id="text" value={text} onChange={handleTextChange} />
<Child name="Child without memo()" text={text} />
<MemoChild name="Child with memo()" text={text} />
</div>
);
};

ReactDOM.render(<Parent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>


看一下这个例子。您会看到按下按钮时,即使 Prop memoname并未更改,未使用 text的 child 也会重新渲染。它仍然会收到一个新的 props对象。

但是,当您在输入中输入内容时,两个组件都会重新渲染,因为 Prop 的 text属性已更改。

还应注意,这只是性能优化。您不应该一直依赖 memo来防止重新渲染。

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

关于javascript - React是否保证 `props`对象引用保持稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60654861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com