我正在尝试更新数组映射内的状态,但它给我一个错误,即 setState
不是 this
上的函数。我怎样才能做到这一点?我的代码片段如下
this.setState({
isLoading: true
});
this.state.questions.map(function(key, value) {
if (key.id === undefined) {
axios
.post("/api/questions/create", key)
.then(response => {
this.setState({
isLoading: true
});
})
.catch(error => {});
} else {
axios
.post("/api/questions/update/" + key.id, key)
.then(response => {
this.setState({
isLoading: true
});
})
.catch(error => {});
}
});
最佳答案
尝试在 map
中使用粗箭头语法。
更改此:this.state.questions.map(function(key, value) {
为此:this.state.questions.map((key, value) => {
An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.
了解有关箭头函数的更多信息,here .
关于javascript - React 访问数组映射中的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60147681/