我正在构建一个react-redux应用程序。当应用启动时,它将向服务器发送登录请求,服务器将使用一些身份验证信息对其进行回复。检索身份验证数据后,应用程序应发送另一个获取数据的请求。我目前在thunk
上执行这些操作的是这样的东西:
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
})
}
为了使代码正常工作,我必须等待login
中的axios响应完成后再运行fetchData
,因为fetchData
需要身份验证数据才能工作。我也不想在fetchData
中分派login
,而是在我的组件中调用它,就像这样:
class App extends Component {
componentDidMount() {
this.props.login()
// how do I dispatch fetchData here?
}
render() {
// stuff
}
}
有什么方法可以使axios顺序调用?
谢谢
答案 0 :(得分:0)
在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()
}
}