状态不更新与 setState 反应

state not updating with setState react

提前感谢您查看我的问题。所以我通过 submitItem 函数从 CreateItem 组件发布到数据库,然后当返回承诺时,我调用 pullAllItems 来获取数据库类别 table 的所有行以更新类别的状态:

反应组件:

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 的回调函数中)。我是新来的反应者,到处寻找我所缺少的东西,但无法在任何地方得到明确的答案。任何帮助是极大的赞赏!

我想你会想要 this.setState(obj) 以便将动态密钥合并到状态中。