我要在rules状态下从api保存这些对象,我需要为该状态内的每个对象添加一个称为editable的新字段。试过这个,但是什么也没做。
componentDidMount() {
Api.getRules(this.state.brand,
this.state.model,
this.state.version,
this.state.minYear,
this.state.maxYear,
this.state.minKm,
this.state.maxKm,
this.state.page + 1,
this.state.rowsPerPage).then((data) => {
if (data) {
this.setState({
rules: data.body,
});
}
});
this.addEditableField();
}
addEditableField = async () => {
let teste = this.state.rules
teste.map((rule)=>{rule["editable"]=false})
await this.setState({ rules: teste })
}
答案 0 :(得分:0)
更改
if (data) {
this.setState({
rules: data.body,
});
}
到
if (data) {
this.setState({
// this dumps all of the rule properties into a new object and
// adds the new fields at the end of it
rules: data.body.map(rule => ({...rule, editable: false })),
});
}
addEditableField
不是异步方法。它不是在进行ajax调用。
答案 1 :(得分:0)
我发现您的实施中存在一些问题
addEditableField
被从错误的地方呼叫。因为将在从后端获取响应之前调用此方法。因此,一旦获取了响应,只有状态会使用没有editable
字段的实际响应进行更新。taste.map
内部的addEditableField
返回任何内容rules
设置为该状态在获取响应后,即在addEditableField
内尝试调用Api.getRules(....).then()
,如下所示
Api.getRules(this.state.brand,
this.state.model,
this.state.version,
this.state.minYear,
this.state.maxYear,
this.state.minKm,
this.state.maxKm,
this.state.page + 1,
this.state.rowsPerPage).then((data) => {
if (data) {
addEditableField(data.body);
}
});
addEditableField = async(rules) => {
let teste = rules.map((rule) => {
rule["editable"] = false;
return rule;
});
this.setState({
rules: teste
})
}
addEditableField
方法也可以如下简化
addEditableField = async(rules) => {
this.setState({
rules: rules.map(rule => ({
...rule,
editable: false
}))
})
}