我目前的代码:
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentWillMount() {
this.getDetails();
}
//this.getDetails() will load this.state.data, which will have multiple records. Each record has many fields, including "Rationale".
//Some other functions
render() {
var resolutionList = this.state.data.map((item, index) =>
<tr key={index} className={(() => { if (item.ScreenChange == "Deleted") return ("danger") })()}>
<td className="">Some</td>
<td className="">Other</td>
<td className="">Table</td>
<td className="">Data</td>
<td className="col-sm-3">
<textarea className="form-control" name={index} id={index} rows="4" cols="50" maxLength="4000" style={{'resize':'none'}}
value={item.Rationale}
onChange={this.handleRationalChange}
/>
</td>
</tr>
);
}
return (
{resolutionList}
)
现在我想强制清除textarea中的数据。我创建了以下函数来重置this.state.data。其他字段已成功更新为空白,除了&#34; Rationale&#34;领域。
通过调试,我可以看到this.state.data [i] .Rationale实际上已经是null了。但是,屏幕仍显示旧值。这里缺少什么?
<button type="button" className="btn btn-default" onClick={() => this.handleNewForm()}>Clear data</button>
handleNewForm = () => {
for (i = 0; i < this.state.data.length; i++) {
this.state.data[i].some = null;
this.state.data[i].other = null;
this.state.data[i].fields = null;
this.state.data[i].Rationale = null;
}
this.forceUpdate();
}
修改
我已经尝试过setState,但它仍然没有清除数据,或者给了我语法错误。
这给了我语法错误:
this.setState( data[i].Rationale : null);
这仍然无法清除数据:
this.setState( this.state.data[i].Rationale = null);
答案 0 :(得分:0)
在handleNewForm
中,您需要使用setState
,而不是州。
handleNewForm = () => {
for (i = 0; i < this.state.data.length; i++) {
this.setState({data[i]: {Rationale: null, other: null}});
}
this.forceUpdate();
}
请注意,您需要确保data[i]
本身存在且不为空,否则您将收到类似"cannot update value of undefined..."
另一种可能有效的方法:
dataObj = {...this.state.data[i]};
dataObj.Rationale = null;
dataObj.other = null;
this.setState({data[i], dataObj});
或
dataObj = {...this.state.data[i], Rationale: null, other: null};
this.setState({data[i], dataObj});
答案 1 :(得分:0)
您需要使用setState()
(并且您尝试这样做是无效的Javascript)。将您的handleNewForm
功能更改为:
handleNewForm = () =>
this.setState({
data: this.state.data.map(dataItem => (
{
...dataItem,
some: null,
other: null,
fields: null,
Rationale: null
}
))
})