首页 > 解决方案 > 在反应中,在 Render() 之前执行 API 调用和重定向的最佳方法是什么?

问题描述

我主要做后端,所以我的 javascript 并不是全部,但我在设计的管理面板中遇到了问题。该网站的某些部分只能由某些用户访问。

每次加载受保护的组件时,我都会向我的 REST 服务器发送一个请求,该服务器返回 200 或 403,200 响应包含一个名为 的键redirect,即False. 所以我的想法是做以下事情:

...
import { Redirect } from 'react-router-dom';
import axios from 'axios';


class MyProtectedComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            authCalled: false,
            redirect: true,
        };
    }

    componentDidMount() {
        console.log("mounting...")
        axios.get('<https://url>',
        {headers: {"Authorization": localStorage.getItem("token")}})
        .then(res => {
            this.setState({
                redirect: res.data.data.redirect,
                authCalled: true,
            });
        })
    }

    render() {
        if (this.state.authCalled === false) {
           return (
               <div className="animated fadeIn">
               <Row>
               <Col>
               authenticating...
               </Col>
               </Row>
               </div>
           )
       }

       if (this.state.redirect === true) {
           return <Redirect to={{pathname: "/nonauthpage"}} />;
       }

   return ( ....... <main code> ..... )

现在,如果服务器发回 200 允许用户访问,则组件加载,但如果没有,页面将卡在该<authenticating>阶段并且永远不会Redirects。

我所有的 javascript 都是自学的,如果我正在做的是执行此类事情的坏习惯,请让我知道如何正确地做到这一点,或者告诉我为什么这不起作用,以便我让它工作。

标签: javascriptreactjsreact-router-dom

解决方案


您正在使用 axios,这意味着如果响应不是 200(或 2XX),then则不会执行,而是需要链接执行.catch如下所示:

componentDidMount() {
    console.log("mounting...")
    axios.get('<https://url>',
    {headers: {"Authorization": localStorage.getItem("token")}})
    .then(res => {
        this.setState({
            redirect: res.data.data.redirect,
            authCalled: true,
        });
    }).catch(error => {
        // You can do additional checks here like e.g. check if the response code is 403 or 401 
        this.setState({
             redirect: true,
             authCalled: true
        });
    })
}

推荐阅读