繁体   English   中英

在Axios调用后设置状态后无法使React组件更新

[英]Can't get React component to update after setting state after Axios call

我有一个应该显示一些类别的React组件。 我正在努力允许用户编辑类别。 我显示一个表单,然后将结果返回到editCategory 然后,我要向Rails后端进行Axios调用。 PUT请求成功,但是当我尝试setState时,它仍在使用PUT请求之前的类别数据。 因此,状态未更新。

我尝试过在PUT请求之后执行GET请求,然后尝试在GET结果之后设置setState,但是它仍然只是拉取PUT请求之前的状态。 尽管如果刷新,我的更改就在那里。 因此后端正在运行。

class Categories extends React.Component { 
 state = { categories: [], toggleEditCat: false,  }

  componentDidMount() {
   axios.get(`/api/menus/${this.props.menuId}/categories`)
     .then( res => {
     this.setState({ categories:res.data })
    })
  }

componentDidUpdate() {
  this.render()
}

editCategory = (name, description, id) => {
 const category = { name, description}
 axios.put(`/api/menus/${this.props.menuId}/categories/${id}`, { 
 category })

 axios.get(`/api/menus/${this.props.menuId}/categories`)
  .then(res => {
   this.setState({ categories: res.data }, () => 
   console.log(this.state.categories))
 })
}  

}

render () {
 return (
  <Segment>
    <div>
      return this.state.categories.map(c => {
      return (
       <ul key={c.id}>
        <h3>Category Name: {c.name}</h3> 
       </ul>
      )
    </div>
  </Segment>
 )
}

在该PUT请求之后,是否有一种方法可以重新呈现,以确保当我发出第二个GET请求时,我得到的是更新的结果? 我以为setState应该重新呈现,但我认为那里缺少一些东西。 谢谢你的帮助。

你不等待你的PUT到您之前完成GET

editCategory = (name, description, id) => {
  const category = { name, description}
  axios.put(
    `/api/menus/${this.props.menuId}/categories/${id}`, 
    { category }
  ).then(() => { // when put is finished, the fire get
    axios.get(`/api/menus/${this.props.menuId}/categories`)
      .then(res => {
        this.setState({ categories: res.data })
      })
  })
}

编辑:将其编写为适当的promise链而不是嵌套promise实际上更好:

editCategory = (name, description, id) => {
  const category = { name, description}
  axios.put(
    `/api/menus/${this.props.menuId}/categories/${id}`, 
    { category }
  ).then(() => { // when put is finished, the fire get
    return axios.get(`/api/menus/${this.props.menuId}/categories`)
  }).then(res => {
    this.setState({ categories: res.data })
  })
}

您同时进行放置和获取操作,因此不会获得更新的值。 您可以使用异步等待

尝试以下代码

editCategory = async (name, description, id) => {
 const category = { name, description}
 const updated = await axios.put(`/api/menus/${this.props.menuId}/categories/${id}`, {category });

 if(updated){
   axios.get(`/api/menus/${this.props.menuId}/categories`)
    .then(res => {
    this.setState({ categories: res.data }, () => 
     console.log(this.state.categories));
    });
  }  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM