React 的动态 table 不会在 onClick 操作后重新呈现
React's dynamic table would not re-render after onClick action
我有一个动态 table,它在更改后不会重新呈现。
renderTableData(data) {
this.setState({ rowData: data });
const temp = this.state.rowData.map((row, index) => {
return (
<tr key={row.Dono}>
// some codes here
<td><button onClick={e => {
let rowData = [...this.state.rowData];
let data = { ...rowData[index] };
// ignore the weird 'TRUE' & 'FALSE'
if (this.state.rowData[index].DateReceived == 'null' || this.state.rowData[index].StockReceived == 'TRUE') {
data.DateReceived = 'null';
data.StockReceived = 'FALSE';
} else {
data.StockReceived = 'TRUE';
}
rowData[index] = data;
this.setState({ rowData: rowData });
}} >{this.state.rowData[index].StockReceived}</button></td>
</tr>
)
});
this.setState({ tableData: temp });
}
按钮应在 onClick 事件后显示 this.state.rowData[index].StockReceived
的正确值。但是,它仍处于初始状态。
在 onClick 事件中再次调用 renderTableData
函数并没有重新渲染 table,而是在 renderTableData
之外调用函数。
我怀疑它与shouldComponentUpdate
有关,但我不确定。
代码沙箱:https://codesandbox.io/s/jovial-yalow-vsk09
注意:CodeSandbox 中的按钮需要点击两次才能呈现其之前的状态,这与根本不重新呈现的浏览器不同。
您不应该试图将 JSX 标记保留在本地状态。这是一个工作示例:https://codesandbox.io/s/stack-overflow-data-table-ifnrn
我有一个动态 table,它在更改后不会重新呈现。
renderTableData(data) {
this.setState({ rowData: data });
const temp = this.state.rowData.map((row, index) => {
return (
<tr key={row.Dono}>
// some codes here
<td><button onClick={e => {
let rowData = [...this.state.rowData];
let data = { ...rowData[index] };
// ignore the weird 'TRUE' & 'FALSE'
if (this.state.rowData[index].DateReceived == 'null' || this.state.rowData[index].StockReceived == 'TRUE') {
data.DateReceived = 'null';
data.StockReceived = 'FALSE';
} else {
data.StockReceived = 'TRUE';
}
rowData[index] = data;
this.setState({ rowData: rowData });
}} >{this.state.rowData[index].StockReceived}</button></td>
</tr>
)
});
this.setState({ tableData: temp });
}
按钮应在 onClick 事件后显示 this.state.rowData[index].StockReceived
的正确值。但是,它仍处于初始状态。
在 onClick 事件中再次调用 renderTableData
函数并没有重新渲染 table,而是在 renderTableData
之外调用函数。
我怀疑它与shouldComponentUpdate
有关,但我不确定。
代码沙箱:https://codesandbox.io/s/jovial-yalow-vsk09
注意:CodeSandbox 中的按钮需要点击两次才能呈现其之前的状态,这与根本不重新呈现的浏览器不同。
您不应该试图将 JSX 标记保留在本地状态。这是一个工作示例:https://codesandbox.io/s/stack-overflow-data-table-ifnrn