gpt4 book ai didi

javascript - 如何使用React来setState并避免递归?

转载 作者:行者123 更新时间:2023-11-28 05:54:32 25 4
gpt4 key购买 nike

我正在使用 React 和 Flask 服务器,并有一个用户可以在其中输入信息的表。当用户编辑单元格、添加新行、删除行等时,此子表会更新 MainApp 的 tableData 状态。

我的问题是,我在 MainApp 中使用 image 状态来存储图像 URL(此 URL 也包含哈希值,因此每次客户端请求信息时它都会发生变化)。但是,我还在 MainApp 中使用 tableData 状态来存储当用户更新表时会发生变化的表信息。这会调用 componentWillUpdate,后者会获取图像 blob,将其转换为 URL 并更新状态 image。正如您想象的那样,这会依次调用 componentWillUpdate ,从而导致递归调用。 React documentation表示不要在 componentWillUpdate 内调用 setState。我很好奇推荐的方法是什么。

我的预期行为是用户编辑表格上的单元格,MainApp 向服务器发送包含表格信息的请求,MainApp 接收图像并相应地更新页面。我不应该使用image状态来存储URL吗?

实现此目的的一种方法是在 componentWillUpdate 中使用 setState 并使用 shouldComponentUpdate 以及基于 globalVariable 的逻辑 (shouldComponentUpdate 将被调用多次),但我很确定这可能不是推荐的方法。

var globalVariable = true
var MainApp = React.createClass({
shouldComponentUpdate : function () {
// logic here using globalVariable
}
componentWillUpdate : function () {
console.log("Get image from server")
fetch('/api/data', {
method: 'POST',
body: JSON.stringify({
tableData: this.state.tableData,
})
})
.then(function(response) {
return response.blob();
}.bind(this))
.then(function(imageBlob) {
this.setState({
image: URL.createObjectURL(imageBlob),
tableData: this.state.tableData
})
}.bind(this))
},
handleTableUpdate : function(newState) {
this.setState({
image: this.state.image,
tableData: newState
});
console.log("Table updated")
},
render : function() {
return (
<div>
<div id="inverter-table" className="col-sm-6">
<MyReactBootstrapTable
onTableUpdate={this.handleTableUpdate}
data={this.state.tableData} />
</div>
<div id="img" className="col-sm-6">
<MyPlot url={this.state.image}></MyPlot>
</div>
</div>
);
}
})

最佳答案

您可以在 componentWillReceiveProps 中识别更改的属性,然后相应地调用 setState。这不会在代码中创建递归。

关于javascript - 如何使用React来setState并避免递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37810644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com