![](/img/trans.png)
[英]How to re-render a particular component in React with setInterval or there is another way?
[英]The correct way to re-render react component from another component
我有一个带有初始 state 的组件 BoardManager
const BoardManager = () => {
const [boards] = useState([
{
name: "Board 1",
link: "dkhgsdfj",
},
{
name: "Board 2",
link: "dkhgsdfj",
},
]);
return (
<div>
{boards.map((val, i) => (
<Board boardName={val.name} />
))}
<AddBoardButton boards={boards} />
</div>
);
};
我有组件 AddBoardButton
function AddBoardButton({ boards }) {
return (
<div className="AddBoardButton">
<button
type="button"
onClick={() => {
boards.push({ name: "added board", link: "to be done" });
}}
>
Add board
</button>
</div>
);
}
我想要的行为:我按下按钮,它添加了新板
问题:
boards.push
确实更改了 BoardManager 的 state,但是我应该如何让 React 以正确的方式重新渲染 BoardManager 的 state 中的更改?board.push 确实更改了 BoardManager 的 state,但是我应该如何让 React 以正确的方式重新渲染 BoardManager 的 state 中的更改?
您正在直接对 state 进行变异,这就是您的组件不重新渲染的原因。 您需要正确更新 state 以触发 state 更新的重新渲染。
要正确更新 state,您需要创建一个新数组并将旧 state 与新数组合并。 您还需要将由useState()
钩子返回的 state 设置器 function 作为道具传递给AddBoardButton
组件。
板子组件:
// destructure state setter function
const [boards, setBoards] = useState([...]);
// pass the state setter function as a prop
<AddBoardButton boards={boards} setBoards={setBoards} />
AddBoardButton 组件:
const handleClick = () => {
const newObject = { name: "added board", link: "to be done" };
const updatedState = [...boards newObject];
setBoards(updatedState);
}
// set the onClick event handler on the button
<button type="button" onClick={handleClick} />
而且,从组件 B 更改组件 A 的 state 是否可行,或者我应该避免这样做吗?
子组件可以更新父组件中存在的 state。
有两种方法可以处理此问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.