【发布时间】:2018-08-11 16:23:14
【问题描述】:
提前感谢您查看我的问题。所以我通过 submitItem 函数从 CreateItem 组件发布到数据库,然后当返回承诺时,我调用 pullAllItems 来获取我的数据库的类别表的所有行以更新类别的状态:
反应组件:
import React, { Component } from 'react';
import CreateItem from './components/CreateItem';
import Categories from './components/Categories';
// stylesheets
import './stylesheets/App.css';
class App extends Component {
constructor() {
super();
this.state = {
categories: [],
tasks: []
};
this.submitItem = this.submitItem.bind(this);
this.pullAllItems = this.pullAllItems.bind(this);
}
componentWillMount() {
fetch('/api/categories')
.then(res => res.json())
.then(res => {
this.setState({
categories: res
});
});
}
submitItem(title) {
const category = {
title
}
fetch('/api/categories', {
method: 'POST',
body: JSON.stringify(category),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(this.pullAllItems('categories'));
}
pullAllItems(type) {
const key = type;
let obj = {};
fetch('/api/' + type)
.then(res => res.json())
.then(res => {
obj[key] = res;
this.setState({
obj
}, () => {
console.log(this.state.categories);
});
});
}
render() {
return (
<div className="App">
<CreateItem submitItem={this.submitItem} />
<Categories categories={this.state.categories} pullAllTasks={this.pullAllItems}/>
</div>
);
}
}
如果我在控制台记录响应,我会得到使用 submitItem 函数发布的附加行;但是,当我在 pullAllItems 函数中更新类别的状态时,状态不会更新(即使在 setState 的回调函数中)。我是新来的反应者,我到处寻找我所缺少的东西,但在任何地方都无法得到明确的答案。任何帮助是极大的赞赏!
【问题讨论】:
-
在
pullAllItems中,this.setState({ obj })等价于this.setState({ obj: obj })。这几乎肯定不是您想要的。 -
添加你正在做的 submitItem 的结尾:
then(this.pullAllItems('categories'),这不应该是:then(() => this.pullAllItems('categories'))吗?否则你直接获取而不等待承诺。 -
另外,在
submitAllItems()中,then(this.pullAllItems(...))会立即被调用。我假设您想将呼叫推迟到fetch()完成之后。你想做fetch(...).then(() => this.pullAllItems())。 -
天哪,你说的都对。返回 promise 后改为调用 pullAllItems。
标签: reactjs components state setstate