我的更改产品名称函数称为 setState,它返回“突变的上一个状态”。我将函数传递给子组件,并通过上下文 API 在子组件中调用它。该函数已成功更新了子级和父级中显示的产品名称,但父级确实触发了重新渲染。父级如何在不重新渲染的情况下更新视图?谁能解释一下设置状态中的上一个状态实际上是什么?
const App = () => {
const [products, setProducts] = useState(initialValues);
const changeProductName = (id, newName) => {
setProducts((prevState) => { //is preState a copy of state?
prevState.products.filter(
(product) => product.id === id
)[0].name = newName; //Mutates prevState
return prevState; //Did I return a new state?
});
};
useEffect(() =>
console.log("I would know when App re-renders")); //No re-render!
return (
<> //Some React Switch and Routers
<div>
{product.map(product=>product.name)} //Successfully Updated!
</div>
<ProductContext value={(products, changeProductName)}>
<ProductPage /> //call changeProductName and it works!
</ProductContext>
</>
);
};
如果我更改的函数不触及 prevState,父级将按预期重新呈现。这种方法更好吗?
//this will trigger parent re-render.
const changeProductName = (id, newName) => {
setProducts((prevState) => {
prevState.products.filter(
(product) => product.id === id
)[0].name = newName;
return prevState;
});
};
慕田峪7331174
红糖糍粑
相关分类