英文:
Cannot see updates from child component through parent's callback (case array and push)
问题
如题。我尝试通过父组件提供的回调从子组件设置组件状态。示例在 https://codepen.io/jadecubes/pen/wvYxKEL 中。
回调函数如下:
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*这是回调*/
info.length = 0;
info.push("Hey!");
setInfo(info);
}}
/>
<h1>{info}</h1>
</>
);
};
点击按钮不会改变文本。但如果像下面这样,它会正常变化。
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*这是回调*/
setInfo(['hey']);
}}
/>
<h1>{info}</h1>
</>
);
};
欢迎提出任何建议。
英文:
As title. I try to set component state from child through callback given by parent. Demo is in https://codepen.io/jadecubes/pen/wvYxKEL
The callback looks like
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*I am callback*/
info.length = 0;
info.push("Hey!");
setInfo(info);
}}
/>
<h1>{info}</h1>
</>
);
};
Clicking button doesn't change the text. But if it's something like below, it changes normally.
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {/*I am callback*/
setInfo(['hey']);
}}
/>
<h1>{info}</h1>
</>
);
};
Any suggestions are welcome.
答案1
得分: 1
不能使用push
方法向存储在React状态中的数组推送项目,因为React状态中的数组是不可变的。这是更新后的代码。请尝试:
const { useState, useEffect } = React;
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {
setInfo([
...info,
"Hey!"
]);
}}
/>
<h1>{info}</h1>
</>
);
};
B = (props) => {
return (
<>
<button
type="button"
onClick={() => {
props.onChange();
}}
>
Click Me!
</button>
</>
);
};
const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<A />);
您可以在react文档中详细了解如何更新数组。
英文:
You can't push items in the array that is stored in react state with push method because arrays store in react state are immutable. Here is the updated code. Try that:-
const { useState, useEffect } = React;
A = () => {
const [info, setInfo] = useState(["Hello world."]);
return (
<>
<B
onChange={() => {
setInfo([
...info,
"Hey!"
]);
}}
/>
<h1>{info}</h1>
</>
);
};
B = (props) => {
return (
<>
<button
type="button"
onClick={() => {
props.onChange();
}}
>
Click Me!
</button>
</>
);
};
const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<A />);
You can read how to update arrays more in details in react docs.
Hope it will be helpful.
答案2
得分: 1
React状态是不可变的。
不应该尝试通过调用push、pop等方法直接更改状态。
应该使用返回新数组的方法,如concat等。
请查阅React文档:
https://react.dev/learn/updating-arrays-in-state
英文:
React state are immutable.
You should not aim to mutate the state directly by calling methods like push, pop
You should use methods that return new arrays like concat, …etc
Check React documentations below:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论