简体   繁体   English

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

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

I have a React component that is supposed to display some categories. 我有一个应该显示一些类别的React组件。 I'm working on allowing a user to edit the category. 我正在努力允许用户编辑类别。 I display a form and then get the results back in editCategory . 我显示一个表单,然后将结果返回到editCategory I'm then making an Axios call to a rails back end. 然后,我要向Rails后端进行Axios调用。 The PUT request is successful, but then when I try to setState, it's still using the data from what categories was before the PUT request. PUT请求成功,但是当我尝试setState时,它仍在使用PUT请求之前的类别数据。 So State is not updating. 因此,状态未更新。

I've tried doing a GET request after the PUT request and then trying to setState after with the GET results, but it still just pulls what State was before the PUT request. 我尝试过在PUT请求之后执行GET请求,然后尝试在GET结果之后设置setState,但是它仍然只是拉取PUT请求之前的状态。 Although if I refresh, my changes are there. 尽管如果刷新,我的更改就在那里。 So the backend is working. 因此后端正在运行。

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>
 )
}

Is there a way to rerender after that PUT request to make sure when I make the second GET request, I'm getting updated results? 在该PUT请求之后,是否有一种方法可以重新呈现,以确保当我发出第二个GET请求时,我得到的是更新的结果? I thought setState was supposed to rerender, but I think I'm missing something there. 我以为setState应该重新呈现,但我认为那里缺少一些东西。 Thanks for any help. 谢谢你的帮助。

You're not waiting for your PUT to finished before your GET 你不等待你的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 })
      })
  })
}

EDIT: it's actually nicer to write it as a proper promise chain instead of nesting promises: 编辑:将其编写为适当的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 })
  })
}

You are doing both put and get at the same time so you won't get updated values. 您同时进行放置和获取操作,因此不会获得更新的值。 You can use async await 您可以使用异步等待

Try with below code 尝试以下代码

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.

相关问题 使用Redux在Axios调用后更新React组件状态 - Updating React Component State after Axios Call using Redux State 在 axios 调用后第一次在 React 的功能组件中没有得到更新 - State does not get updated in functional component in React for the first time after axios call 如何在 axios 调用后使用 useReducer 获取反应组件以重新渲染? - How to get react component with useReducer to rerender after axios call? 状态在axios调用后未更新 - State not updating after axios call in react 如何在异步调用反应后测试 state 更新和组件重新渲染 - How to test state update and component rerender after async call in react 警告:更新上下文并重定向到另一个页面后,无法在未安装的组件上执行 React state 更新 - Warning: Can't perform a React state update on an unmounted component after update context and redirect to another page 更新到状态后,React组件不会重新渲染 - React component doesn't rerender after update to state 状态更改后,React不会更新组件 - React doesn't update component after state changes 在 state 更新后 React useEffect 不会重新加载我的组件 - React useEffect doesn't reload my component after state update 添加等待标记以调度后,无法对未安装的组件执行反应 state 更新 - Can't perform a react state update on an unmounted component after adding await tag to dispatch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM