首页 > 解决方案 > 如何使用先前状态更新字符串的状态

问题描述

我是 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>;*

标签: javascriptreactjscomponentsstatesetstate

解决方案


使用先前状态更改状态的方式是这样的:

this.setState(prevState => {
   return {HTMLTable: prevState.HTMLTable + whatever you want};
});

推荐阅读