首页 > 解决方案 > 在.then 中的 setState 之后,组件在 Axios 调用之后不重新渲染

问题描述

在下面的代码中,我希望组件在和ListItem上刷新。handleOnAddhandleOnUpdate

这些函数作为道具传递给AddItemEditItem组件。

ListItem组件item从的App状态获取它的 s。

它适用于handleOnDelete,因为我添加了.then(this.handleChange()). 我对 and 做同样的事情handleOnAddhandleOnUpdate但那些不会触发重新加载....

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      items: [{ "_id": { "$oid": "5f1fda0169e133382277a4ef" }, "title": "Blabla", "description": "adfadfd211233", "__v": 0 }]
    }

    this.handleOnUpdate = this.handleOnUpdate.bind(this);
    this.handleOnAdd = this.handleOnAdd.bind(this);
    this.handleOnDelete = this.handleOnDelete.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    Axios.get('http://localhost:4200/items')
      .then(res => {
        this.setState({ items: res.data })
      })
      .catch(function (error) {
        console.log(error)
      })
  }

  handleChange() {
    Axios.get('http://localhost:4200/items')
      .then(res => {
        this.setState({ items: res.data })
      })
      .catch(function (error) {
        console.log(error)
      })

  }

  handleOnAdd(item) {
    Axios.post('http://localhost:4200/items/add/', item)
      .then(res => console.log(res.data))
      .then(this.handleChange());
  }

  handleOnUpdate(id, item) {
    Axios.post('http://localhost:4200/items/update/' + id, item)
      .then(res => console.log(res.data))
      .then(this.handleChange());

  }

  handleOnDelete(id) {
    Axios.get('http://localhost:4200/items/delete/' + id)
      .catch(err => console.log(err)).then(this.handleChange());
  }

  render() {
    return (
        .... Router stuff....
        <Route exact path='/add' render={(props) => <AddItem {...props} handleOnAdd={(item) => this.handleOnAdd(item)} />} />
        <Route path='/edit/:id' render={(props) => <EditItem {...props} handleOnUpdate={(id, item) => this.handleOnUpdate(id, item)} />} />
        <Route path='/index' render={(props) => <ListItem {...props} handleOnDeleteInApp={(id) => this.handleOnDelete(id)} items={this.state.items} />} />
        .... Router stuff....

    );
  }
}

谁能发现为什么handleOnDelete以及随之而来的状态更改成功触发了重新渲染ListItem,但其他功能却没有?

标签: javascriptreactjsaxiosreact-router-dom

解决方案


.then(this.handleChange());

此代码handleChange 立即调用,然后将其结果传递给.then. 所以这段代码不等待前几行的添加/更新/删除。如果handleOnDelete工作正常,那么我认为这只是由于竞争条件。

您应该将所有三个函数中的这一行更改为:

.then(() => this.handleChange())

或者

.then(this.handleChange);

推荐阅读