SetState doesn't work with with data from server

杀马特。学长 韩版系。学妹 提交于 2020-06-07 07:11:26

问题


Hi I'm programming a page with React hooks and I'm trying to set the data I get from the server in to the state. SOmehow it doesnt work. I get the data from the server, but i cant map it to the state. Any Ideas what the problem could be?

const [workouts, setWorkouts] = React.useState([]);
useEffect(() => {
        apiGet(fitnessaryEndPoints.workouts.getAllWorkouts)
            .then(
                response => {
                    setWorkouts([...workouts, response.data])
                    console.log(response)
                    console.log(workouts)

                }
            ).catch(
            error => {
                console.log(error)
            }
        )
    }, [])

data from Server


回答1:


setWorkouts is async method, so you will not get updated data right below it.

setWorkouts([...workouts, response.data])
console.log(workouts) //<--- this will not reflect the updated data

Else your code is good, it will be reflected in DOM if you are looping and showing it


Run the below code snippet and check HTML and console both, that will clear the flow.

const { useState , useEffect } = React;

const App = () => {

  const [users,setUsers] = useState(['Vivek' , 'Darsh']);

  useEffect(() => {
    setTimeout(() => {
      setUsers([...users, "Vivan" , "Darshita"]);
      console.log(users);
    },2000);
  },[]);

  return (
    <div>
      { users.map(user => <p>{user}</p>) }
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>


来源:https://stackoverflow.com/questions/61716831/setstate-doesnt-work-with-with-data-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!