我是一个非常新的反应者,不了解为什么状态更改后我的子元素没有重新呈现。一切正常,直到您点击添加列按钮。这会改变状态的局限性,实际上,董事会似乎已经重新提交,但列却没有。
const Board = function() {
const [board, setBoard] = useState([]);
useEffect(() => {
console.log(boardJSON);
setBoard(boardJSON.board);
}, [])
const addColumn = () => {
console.log('addColumn');
let inx = board.length + 1;
let col = {userId: 1, columnId: inx, header: 'Bob', cards: []};
board.push(col);
board[0].header = "Marge";
let cardx = {"cardId": 4, "desc": "Break sound barrier", "status": "incomplete"};
board[0].cards.push(cardx);
board[1].cards[1].status = "destroyed";
setBoard(board);
};
return (
<div>
<div className="board">
{console.log("parent rerendering", board) // we get this far, but columns don't rerender
}
{board.map((column) => (
<Column key={column.columnId} column={column} />
))}
</div>
<button className="add-column-button" onClick={() => {addColumn()}}>
<img src={plus_sm} />
Add new column
</button>
{console.log("we got to the end", board) // did we get to the end?
}
</div>
);
};
export default Board;
这是我在控制台上看到的。 addColumn之后,屏幕上没有任何变化,并且我们没有收到“渲染列”消息。只是似乎跳过了重新映射。
parent rerendering Array(0)
Board.js:42 we got to the end Array(0)
Board.js:11 Object
Board.js:31 parent rerendering Array(2)
Board.js:42 we got to the end Array(2)
Column.js:21 rendering column number 1
Column.js:21 rendering column number 2
Column.js:10 column rendering, props received Object
Column.js:10 column rendering, props received Object
Board.js:16 addColumn
Board.js:31 parent rerendering (3) [{…}, {…}, {…}]
Board.js:42 we got to the end (3) [{…}, {…}, {…}]
万一您想知道,这是一个react-dnd应用程序,但是我把所有的dnd都拿出来了,以防引起问题。不是。
答案 0 :(得分:0)
这是因为您改变了状态。有关为何不直接修改反应状态的信息,请参见此link。另请参阅this example,我是为了让您了解如果直接更改状态会发生什么情况。
您的情况应该是:
const addColumn = () => {
console.log('addColumn');
let inx = board.length + 1;
let col = {userId: 1, columnId: inx, header: 'Bob', cards: []};
const newBoardContent = [...board];
newBoardContent.push(col);
newBoardContent[0].header = "Marge";
let cardx = {"cardId": 4, "desc": "Break sound barrier", "status": "incomplete"};
newBoardContent[0].cards.push(cardx);
newBoardContent[1].cards[1].status = "destroyed";
setBoard(newBoardContent);
};