我正在构建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
之前,我必须等待fetchData
中的axios响应完成,因为fetchData
需要身份验证数据才能起作用。我也不想在fetchData
中分派login
,而是在我的组件中调用它,如下所示:
class App extends Component {
componentDidMount() {
this.props.login()
// how do I dispatch fetchData here?
}
render() {
// stuff
}
}
有什么方法可以使axios顺序调用?
谢谢
在LOGIN_SUCCESS类型或您可以说is_Authenticated的内容后的auth reducer中:true,因此在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()
}
}