【问题标题】:It seems Axios does not update the state when use with async and await与 async 和 await 一起使用时,Axios 似乎没有更新状态
【发布时间】:2021-03-08 10:49:52
【问题描述】:

当我将 Axios 与 async 和 await 一起使用时,如何立即更新状态数据?似乎没有立即更新状态数据。非常感谢并非常感谢。这是代码示例:

const[dbdata,setDBData] = useState([])  


  useEffect(async() => {
        const response = await Axios.get('http://localhost:5000/api/posts/allpost', {withCredentials:true})
        setDBData(response.data)
    
    }, [])

    const GetPost = async(id) =>{
        const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true})
        const getData = dbdata.map(item => {
            if(item._id==response._id){
                return response
            }
            else{
                return item
            }
           
        })
        console.log(getData)
        setDBData(getData)
    }

【问题讨论】:

标签: reactjs axios


【解决方案1】:

不支持useEffect(async () => ...),但您可以在效果内调用异步函数。

试试:

useEffect(() => {
 
  const GetPost = async(id) =>{
       const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true});
       const getData = dbdata.map(item => {
           if(item._id==response._id){
              return response;
           }
           else{
              return item;
           }
               
        })
        console.log(getData);
        setDBData(getData);
  }
   GetPost();
}, [])

    

编辑:

或者:

useEffect(() => {
   GetPost();
}, []);

const GetPost = async(id) =>{
       const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true});
       const getData = dbdata.map(item => {
           if(item._id==response._id){
              return response;
           }
           else{
              return item;
           }
               
        })
        console.log(getData);
        setDBData(getData);
}
 

    

【讨论】:

  • 谢谢,但是如何在按钮 onClick 中调用 GetPost 函数,因为它在 useEffect 中?再次感谢
  • 将 GetPost 移到 useEffect 之外。
  • 创建另一个state,然后触发useEffect。例如:const [click, setClick] = useState(false)。然后在useEffect(() => GetPost, [click])。剩下的就是更新onClick 事件中的click,如下所示:onClick={() = > setClick(true)}。将onClick 事件放在你想要的button
  • 我从异步更改为非异步但状态数据仍未更新? const GetPost = (id) =>{ Axios.put('localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true}).then(response => { const getData = dbdata.map(item => { if (item._id==response._id){ return response } else{ return item } }) setDBData(getData) }) }
  • 尝试使用 setDBData([...getData])。
猜你喜欢
  • 2018-09-03
  • 1970-01-01
  • 2018-03-25
  • 2020-03-08
  • 1970-01-01
  • 2015-08-18
  • 2018-04-14
  • 2020-09-10
  • 1970-01-01
相关资源
最近更新 更多