簡體   English   中英

作為回應,在Render()之前執行API調用和重定向的最佳方法是什么?

[英]In react, what is the best way to perform an API call and redirect before Render()?

我主要是在做后端,所以我的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>階段,並且永遠不會Redirect

我所有的JavaScript都是自學成才的,如果我做的事情對執行此類操作是不好的做法,請讓我知道如何正確執行此操作,或者告訴我為什么它不起作用,以便使它起作用。

您正在使用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
        });
    })
}

您可以按以下方式自定義代碼以使其正常工作

....
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,
            });
        }).catch(err => {
            this.setState({
                redirect: true,
                authCalled: true,
            });
        })
    }

    render() {
        if (this.state.authCalled === true) {
            if (this.state.redirect === true) { 
                return <Redirect to={{pathname: "/nonauthpage"}} />;
            } else {
                  return ( ....... <main code> ..... ) 
            }
        }
        else {
            return (
                <div className="animated fadeIn">
                    <Row>
                        <Col>
                        authenticating...
                        </Col>
                    </Row>
                </div>
            )
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM