在axios完成获取后,React不会设置状态 [英] React doesn't set state after axios finished fetching

查看:122
本文介绍了在axios完成获取后,React不会设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写客户端代码以使用React和react-router进行身份验证.在下面的代码中,我想检查服务器上的jwt令牌.之后,我将从服务器获取response.data.access,并将其设置为客户端上的access变量.但是,即使将true记录在控制台中,它也会将false传递到受保护的路由.如何正确设置access?我猜问题出在异步代码中,调用setAccess函数时无需等待axios提取.

I'm writing client side code for authentication with React and react-router. In the code below, I want to check jwt token on the server. After that, I'll get response.data.access from server and I want to set it to access variable on client. But it seems it passes false to the protected route even if it logs true in the console. How can I set access properly? I guess the problem is in asynchronous code, and setAccess function is called without waiting for axios to fetch.

// imports

function App() {

  const [access, setAccess] = useState(false);

  useEffect(() => {
    fetch();
  }, [access]);

  const fetch = async () => 
    await axios.get('http://localhost:7000/user/check-token')
      .then(response => {
        // response.data.access is a boolean variable coming from server
        console.log(response.data.access)
        setAccess(response.data.access);
      });

  return (
    <Router>
      <Switch>

        // other routes

        <Protected path='/user/dashboard' access={access}>
          <Dashboard userData={userData} />
        </Protected>

      </Switch>
    </Router>
  );
}

export default App;

这是受保护的路线

 const Protected = ({ children, access, ...rest }) => {

    return (
      <div>
        <Route {...rest} render={(props) => (
          access === true
            ? children
            : <Redirect to={{
                pathname: '/user/login',
                state: { from: props.location }
              }} />
        )} />
      </div>

    );
  }

您能解释一下发生了什么,我该怎么办?

Could you please explain what is happening and what should I do?

推荐答案

我已经解决了这个问题.好吧,我只是添加了一个加载屏幕,以等待一段时间来获取数据,这解决了我的问题.

I have solved this problem. Well, I just added a loading screen to wait some time while data is fetching, and it solved my problem.

const Protected = ({ children, access, ...rest }) => {


    return (
      <div>
        <Route {...rest} render={(props) => {
         if (access === null) {  // if access is null, the data is still being fetched
          return <h1>Loading...</h1>  // display loading hardcoded loading screen while it's not fetched
         } else {
          if (access === true) {
            return children
          } else {
            return <Redirect to={{
              pathname: '/user/login',
              state: { from: props.location }
            }} />
          }

         }

        }} />
      </div>

    );
  }

这篇关于在axios完成获取后,React不会设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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