如何在渲染路由之前调用API并接收其信息? [英] How to call the API and receive its information before rendering the routes?

查看:34
本文介绍了如何在渲染路由之前调用API并接收其信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React应用,其中定义了一些公用/专用路由,我需要将用户信息传递到专用路由.我正在尝试调用API(返回用户详细信息)并在渲染路由之前接收它,但无法使其正常工作-在获取响应之前渲染了路由,因此用户获得了空值.在这种情况下,我尝试使用async/await失败.或者,如果有人知道一种更好的方法.谢谢!

I have a React app with some public/private routes defined and I need to pass the user information into the private route. I'm trying to call the API (that returns the user details) and receive it before rendering the routes but can't make it work - the routes are being rendered before getting the response so the user is getting empty value. I've tried to use async/await without success in this case. Or maybe if anyone know a better approach for this. Thanks!

export const Routes = () => {

    const user = axios.get('/login').then(function(res) { return res })

    return (
        <Switch>
            <PrivateRoute exact path="/" component={Home} user={user} />
            <Route component={Error404} />
        </Switch>
    )
}

推荐答案

在知道axios请求的响应后,如何使用状态创建路由?
像这样:

What about using state to create the routes after you know the response from your axios request?
Something like this:

import React, { useState, useEffect } from "react";
import { Route, Switch, PrivateRoute } from "react-router-dom";
import axios from "axios";

import Home from "./Home";
import Error404 from "./Error404";

const Routes = () => {
  const [user, setUser] = useState("");

  useEffect(() => {
    axios.get("/login").then(res => {
      setUser(res);
    });
  }, []);

  return user ? (
    <Switch>
      <PrivateRoute exact path="/" component={Home} user={user} />
      <Route component={Error404} />
    </Switch>
  ) : null;
};

export default Routes;

您可以改进它,具体取决于您的回复和其他组件.

You can improve it, depending on your responses and other components.

这篇关于如何在渲染路由之前调用API并接收其信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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