[英]Changing state in a function from a button click does not trigger a rerender in React.js
我在React和一個按鈕中有一個單元格矩陣-小矩形。 在單擊按鈕時,我要清除所有單元格。 首先,我創建了許多帶有一些非空單元格的空單元格,並將其傳遞到CellGrid組件中,這使所有單元格都很好。 我將按鈕onClick鏈接到一個函數,該函數會更改狀態(this.state.cells),但不會觸發子組件(CellGrid)中的重新渲染。
class Playfield extends React.Component {
constructor(props){
super(props);
this.clearButtonClick = this.clearButtonClick.bind(this);
}
componentWillMount(){
var arr = [];
for (var i=0; i < 64*64; ++i){ // all empty cells at first
arr.push({id:i, status: "empty"});
}
for (var i=0; i < startCells.length; ++i){ // mark special cells
var newIndex = startCells[i].x + 64*startCells[i].y;
arr[newIndex].status = "alive";
}
this.setState({ // change state
cells: arr
});
}
clearButtonClick(){
console.log("clear")
var newArr = [];
for (var i=0; i < this.state.cells.length; ++i){ // all empty cells again
newArr.push({id:i, status: "empty"});
}
this.setState({ // change state --- NOT UPDATING THE RENDER
cells: newArr
});
}
render(){
return (
<div className="Playfield">
<CellGrid grid_cells={this.state.cells}/>
<Button onClick={this.clearButtonClick}>CLEAR</Button>
</div>
);
}
}
而CellGrid看起來像這樣。
class CellGrid extends React.Component {
constructor(props){
super(props);
this.renderCells = this.renderCells.bind(this);
}
renderCells(){
return (this.props.grid_cells.map(function(cell){
return (
<Cell id={cell.id} status={cell.status}/>);
}));
}
render(){
return (
<div className="CellGrid">
{this.renderCells()}
</div>
);
}
}
有人提示嗎? 相關問題都以錯誤的方式改變了狀態。
它實際上在工作; 您可以將控制台日志放入CellGrid的render方法中,以查看單擊清除后觸發了渲染。 問題實際上出在<Cell>
組件內。
<Cell>
似乎在初始安裝只使用從道具狀態,其中它復制status
從道具到它自己的內部狀態,然后使該細胞的來自this.state.status
代替this.props.status
。 我想您是使用onClick切換單元格的方式。 您可能想要做的是擺脫<Cell>
中的本地狀態,並始終使用this.props.status
呈現它,還只需將onClick從<Playfield>
傳遞到<CellGrid>
,然后從<CellGrid>
傳遞給每個<Cell>
。
另外,確保從數組渲染組件時都使用key=
屬性(例如<CellGrid>
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.