[英]React Component does not re rendering when updating an object in state hooks
为什么 state 更新时这个组件没有更新? 但是,当文件更新(如编辑和保存代码)时,组件将重新渲染并显示更新后的 state 中的正确值。 这是代码
import { useReducer } from "react";
import "./styles.css";
const init = [
{
name: "Car",
stock: 100
},
{
name: "Truck",
stock: 50
}
];
const reducer = (state, action) => {
if (action.type === "add") {
state[0].stock++;
return state;
} else {
return state;
}
};
export default function App() {
const [state, dispatch] = useReducer(reducer, init);
const addCarStock = () => {
dispatch({ type: "add" });
};
return (
<div>
<p>Car Stock : {state[0].stock}</p>
<button onClick={addCarStock}>Add Car Stock</button>
</div>
);
}
可以在沙箱中打开这段代码。io
当你做state[0].stock++;
. 它更改了现有数组(您实际上可以通过将console.log(state);
放在 reducer 函数的第一行来检查更新的数组),并且当 react 进行渲染时,它会进行浅比较(引用检查)并忽略重新渲染假设它是同一个数组(因为 prev 和 new state 指的是同一个实例)。
您需要使用更改创建一个新的数组实例 ( state
) 并将其返回。
const reducer = (state, action) => {
if (action.type === "add") {
return state.map((item,itemIndex) => {
if(itemIndex === 0){
return {...item, stock: item.stock + 1}
} else {
return item;
}
});
} else {
return state;
}
};
代码沙箱 => https://codesandbox.io/s/recursing-davinci-iid5h?file=/src/App.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.