3 回答

TA貢獻1847條經驗 獲得超7個贊
使用先前狀態更改狀態的方式是這樣的:
this.setState(prevState => {
return {HTMLTable: prevState.HTMLTable + whatever you want};
});

TA貢獻1911條經驗 獲得超7個贊
你不應該在 React 的循環中使用 setState 函數。通過查看您的代碼,您不需要在循環中使用狀態變量。你可以做的是擁有一個局部變量,在循環內更新它,最后將它存儲回狀態。
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
HTMLTable : ""
}
createGrid () {
let HTMLTable = ""; // Use local varibale
for(let row = 0; row <= 20;row++)
{
let currentHTMLRow = `<tr id = "Row ${row}">`;
for(let col = 0; col < 50; col++)
{
let newNodeId = `${row}_${col}`;
let NodeClass = "unvisited";
currentHTMLRow = currentHTMLRow +`<td id = "${newNodeId}" class = "${NodeClass}"></td>`
}
HTMLTable += `${currentHTMLRow}</tr>`;
}
this.setState({HTMLTable}); // Store it back to the state.
let chart = document.getElementById("grid");
chart.innerHTML = HTMLTable;
}
}
添加回答
舉報