我将 React 与 Flask 服务器一起使用,并且有一个用户可以输入信息的表格。tableData当用户编辑单元格、添加新行、删除行等时,此子表会更新 MainApp 的状态。
我的问题是我image在 MainApp 中使用状态来存储图像 URL(此 URL 也包含哈希,因此每次客户端请求信息时它都会更改)。但是,我还使用tableDataMainApp 中的状态来存储用户更新表时更改的表信息。该调用componentWillUpdate依次获取图像 blob,将其转换为 URL 并更新状态image。这反过来会调用componentWillUpdate您可能想象的导致递归调用。React 文档说不要调用setStateinside 。componentWillUpdate我很好奇推荐的方法是什么。
我的预期行为是用户编辑表格上的单元格,MainApp 向服务器发送带有表格信息的请求,MainApp 接收图像并相应地更新页面。我不应该使用image状态来存储 URL 吗?
一种方法是使用setState和componentWillUpdate使用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>
);
}
})