javascript - 如何使用先前状态更新字符串的状态
问题描述
我是 React 和 Javascript 的新手。我有一个类组件,其构造函数和函数如下所示:
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
HTMLTable : ""
}
createGrid ()
{
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>`
}
this.state.HTMLTable += `${currentHTMLRow}</tr>`;
}
let chart = document.getElementById("grid");
chart.innerHTML = this.state.HTMLTable;
}
}
这会产生预期的效果,但我已被警告不要像这样更改状态的值
this.state.HTMLTable += `${currentHTMLRow}</tr>`;
*如何在每次循环迭代时使用 setState() 更改 HTMLTable 字符串的状态: this.state.HTMLTable += ${currentHTMLRow}</tr>
;*
解决方案
使用先前状态更改状态的方式是这样的:
this.setState(prevState => {
return {HTMLTable: prevState.HTMLTable + whatever you want};
});
推荐阅读
- complexity-theory - 最短哈密顿路径是 NP 难的吗?
- c# - C# WPF:当窗口关闭时,如何调用具有数据绑定的方法?
- php - 图像不保存在公用文件夹 laravel
- javascript - Promise 函数返回未定义
- jquery - 我想在实时搜索后单击标题以获取所有信息和星球大战角色信息时创建一个事件
- python - 出现错误:步幅的长度应为 1、3 或 5,但对于 2D CNN - LSTM 为 2
- pentaho - 在 Pentaho 中插入/更新变量时找不到字段?
- angular - Nativescript- imagecropper 返回一个空对象
- c++ - 连接空字符串的问题
- javascript - Electron:将应用程序图标添加到任务栏的右下角