【问题标题】:Wait for previous axios response to complete before sending next request在发送下一个请求之前等待上一个 axios 响应完成
【发布时间】:2020-08-06 23:39:47
【问题描述】:

我正在构建一个 react-redux 应用程序。当应用程序启动时,它会向服务器发送一个登录请求,服务器会回复一些身份验证信息。检索身份验证数据后,应用程序应发送另一个请求以获取数据。我目前正在为我的thunks 执行这些操作:

const login = () => (dispatch, getState) => {
    axios.get('/login/').then(res => {
        // The user doesn't have to provide their username in this case. The backend handles 
        //  authentication for us automatically and sends back the auth data
        let {username, staff_id, first_name, last_name, groups} = res.data
        dispatch(auth(username, staff_id, first_name, last_name, groups))
    }) // save authentication info to redux state
}

const fetchData= () => (dispatch, getState) => {
    let myUsername = getState().auth.username
    axios.get(`/staff/${myUsername}`).then(res => {
       // stuff
    })
}

为了使代码工作,我必须在运行fetchData 之前等待login 中的axios 响应完成,因为fetchData 需要身份验证数据才能工作。我也不想在login 中调度fetchData,而是在我的组件中调用它,如下所示:

class App extends Component {
    componentDidMount() {
        this.props.login()
        // how do I dispatch fetchData here?
    }

    render() {
         // stuff
    }
}

有什么方法可以让 axios 调用顺序?

谢谢

【问题讨论】:

    标签: reactjs redux react-redux axios redux-thunk


    【解决方案1】:

    在 LOGIN_SUCCESS 类型或您可以说 is_Authenticated: true 之后的 auth reducer 中,因此在 App 组件中您可以查看当前用户是否登录。

    减速器示例:

    import {LOGIN_SUCCESS} from '../types'  
    const authState = {
        isAuthenticated: false
    }
    
    export default (state=authState, action) => {
        switch(action.type){
            case LOGIN_SUCCESS:
                return {
                    ...state,
                    isAuthenticated: true,
                }
            ...
            default:
                return state
    

    应用组件示例:

    import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    import {fetchData} from './actions' // actions route
    import {connect} from 'react-redux'
    
    class App extends Component {
        static propTypes = {
            is_Authenticated: PropTypes.bool.isRequired,
            fetchData: PropTypes.func.isRequired
        }
        componentDidMount = () => { 
            if(this.props.is_Authenticated){
                this.props.fetchData()
            }
        }
    

    【讨论】:

    • 我已经想到了,但这并没有回答如何在我的 App 组件中调用 fetchData 的问题?
    • 这个问题是(我认为)componentDidMount 只被调用一次。所以,如果我没有通过身份验证,那么条件为 false 并且 fetchData 不会运行。相反,我必须以某种方式观察状态并在 isAuthenticated 更改时调度 fetchData,这是我目前正在努力解决的问题。
    • 看看github.com/mr0b0t0/basic-authorization。这很简单。简而言之,这里要做的第一件事是通过检查登录操作后存储的令牌来加载用户
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多