SetState不适用于服务器中的数据 [英] SetState doesn't work with with data from server

查看:57
本文介绍了SetState不适用于服务器中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React钩子对页面进行编程,并且试图将从服务器获取的数据设置为状态.怎么它不起作用.我从服务器获取数据,但无法将其映射到状态.任何想法可能是什么问题吗?

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)
            }
        )
    }, [])

来自服务器的数据

推荐答案

setWorkouts是异步方法,因此您将无法在其下获取更新的数据.

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

否则您的代码很好,如果您循环并显示它,它将反映在DOM中

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

运行以下代码段,并检查HTML和控制台,这将清除流程.

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>

这篇关于SetState不适用于服务器中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆