【发布时间】:2021-05-13 11:40:05
【问题描述】:
代码:
class Table extends Component {
constructor(props)
{
super(props);
this.state = {
body: Body
}
}
onChangeHandler = (event, index) => {
const value = event.target.value;
const body = this.state.body;
body[index] = value;
this.setState(prevState => ({
...prevState,
body: body
}))
}
render() {
const heads = Headers.map((element, index) => <th key = {"__trow__" + index}>{element}</th>);
const body = this.state.body.map((element, index) => <td key = {"__trow_body__" + index}>
<div className = {classes.EditFieldCell}>
<input type = {element.inputType}
className = {classes.EditFieldCellInput}
value = {element.title}
onChange = {(event) => this.onChangeHandler(event, index)}
>
</input>
</div>
</td>
);
return <table className = {classes.prettyTable}>
<thead>
<tr>
{
heads
}
</tr>
</thead>
<tbody>
<tr>
{
body
}
</tr>
</tbody>
</table>
}
}
export default Table;
我尝试通过扩展运算符 this.setState、Object.assign 更新状态,但它们似乎都不起作用。我无法理解我的状态究竟是在什么时候失控的。
在哪里Headers = ["A","B","C"]
和
正文 = [ {title: "Check 1",inputType: "text"}, {title: "Check 2 B",inputType: "text"},{title: "Check 1",inputType: "text"}]
【问题讨论】:
-
你在这里改变你的状态:
body[index] = value;。 Never mutate state. -
哦,我明白了......那么这里有什么更好的选择?试过:
const body = [...this.state.body];这给了我同样的警告。
标签: reactjs