简体   繁体   English

无法在我的本地 state 中使用钩子在反应中设置响应数据

[英]Unable to set response data in my local state using hooks in react

I am using Functional components and am a beginner.I am receiving the response from API successfully but when I am setting it to the local useState variable, it still remains empty.I am unable to understand how to fix this.我正在使用功能组件并且是初学者。我成功地收到了来自 API 的响应,但是当我将其设置为本地 useState 变量时,它仍然是空的。我无法理解如何解决这个问题。

Approach 1:方法一:

const [sites,setSites]=useState([]);
useEffect(()=>{
    getAllSites().then(res=>{
      console.log("res",res.sites);//response received successfully
      setSites(res.sites);
      console.log(sites);//return empty array
    })
    .catch(err=>{
      console.log("Error:",err);
    })
  },[])

Approach 2:方法二:

const [sites,setSites]=useState([]);
useEffect(()=>{
    getAllSites().then(res=>{
      console.log("res",res.sites);
    },(res)=>{
     setSites(res);//thought maybe because of async nature, so tried using callback but still empty 
})
    .catch(err=>{
      console.log("Error:",err);
    })
  },[])

Can someone help me out with this?有人可以帮我解决这个问题吗?

Updating state in react will not happen synchronously.在 react 中更新 state 不会同步发生。 That means when you call setSites the state will not get updated then and there rather the changes or the updated state will be available in the next render.这意味着当您调用setSites时,state 将不会得到更新,而更改或更新的 state 将在下一次渲染中可用。

In order to see if that is working or not, we can make use of useEffect hook by passing the state variable as dependency为了查看这是否有效,我们可以通过将state变量作为依赖项传递来使用useEffect钩子

 const {useState, useEffect} = React; const getAllSites = () => { return new Promise(res => { setTimeout(() => { return res({sites:[{id:1, name:"Google"}, {id:2, name:"Facebook"}]}); }, 500) }) } const App = () => { const [sites,setSites] = useState([]); useEffect(()=>{ getAllSites().then(res=>{ //console.log("res",res.sites);//response received successfully setSites(res.sites); }).catch(err=>{ console.log("Error:",err); }) },[]); useEffect(() => { //This will print on mount as well as when there's any change in `sites` console.log(sites); }, [sites]) return <p>App</p> } ReactDOM.render(<App />, document.getElementById("react"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script> <div id="react"></div>

And, while the data is being fetched you can display the loading indication and once the data is available you can hide loading and display the actual data.而且,在获取数据时,您可以显示加载指示,一旦数据可用,您可以隐藏加载并显示实际数据。

You are doing everything correct.你做的一切都是正确的。 But you cannot see immediately updated value in the sites (obviously it is const) so you will see on the next render cycle, when your functional component will be run and react will assign new value to the sites.但是您无法在站点中看到立即更新的值(显然它是 const),因此您将在下一个渲染周期看到,当您的功能组件将运行时,react 将为站点分配新值。 Once state updated new rerendering will happen.一旦 state 更新,就会发生新的重新渲染。 Just add console.log(sites) to the top level of your functional component只需将console.log(sites)添加到功能组件的顶层

const [sites,setSites]=useState([]);
console.log(sites);
useEffect(()=>{...},[]);

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

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