【发布时间】: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