如何使用以前的状态更新字符串的状态

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


撒科打诨
浏览 99回答 3
3回答

aluckdog

使用先前状态更改状态的方式是这样的:this.setState(prevState => {&nbsp; &nbsp;return {HTMLTable: prevState.HTMLTable + whatever you want};});

Smart猫小萌

你不应该在 React 的循环中使用 setState 函数。通过查看您的代码,您不需要在循环中使用状态变量。你可以做的是拥有一个局部变量,在循环内更新它,最后将它存储回状态。class MyComponent extends Component {constructor(props) {&nbsp; &nbsp; super(props)&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp;HTMLTable : ""&nbsp;&nbsp;&nbsp; &nbsp; }createGrid () {&nbsp; &nbsp; let HTMLTable = ""; // Use local varibale&nbsp; &nbsp; for(let row = 0; row <= 20;row++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let currentHTMLRow = `<tr id = "Row ${row}">`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let col = 0; col < 50; col++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let newNodeId = `${row}_${col}`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let NodeClass = "unvisited";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentHTMLRow = currentHTMLRow +`<td id = "${newNodeId}" class = "${NodeClass}"></td>`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HTMLTable += `${currentHTMLRow}</tr>`;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; this.setState({HTMLTable}); // Store it back to the state.&nbsp; &nbsp; &nbsp; let chart = document.getElementById("grid");&nbsp; &nbsp; &nbsp; chart.innerHTML = HTMLTable;&nbsp; &nbsp; }}

青春有我

最简单的方法:this.setState({&nbsp; &nbsp; HTMLTable: this.state.HTMLTable+=currentHTMLRow});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript