状态未使用setState进行更新反应

问题描述 投票:1回答:1

提前谢谢你看看我的问题。所以我通过submitItem函数从CreateItem组件发送到DB,然后当返回promise时,我调用pullAllItems来获取我的DB的categories表的所有行以更新类别的状态:

反应组件:

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函数POST的附加行;但是,当我更新pullAllItems函数中的类别状态时,状态不会更新(即使在setState的回调函数中)。我是新来的反应,并且到处寻找我能看到我所缺少的东西,但无法在任何地方获得明确的答案。任何帮助是极大的赞赏!

reactjs components state setstate
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.