Javascript React redux等待来自api的数据
我正在使用react和redux与axios、thunk和promises中间件进行注册表单。首先,我想等待用户列表。然后,我想检查,如果不是post用户,则具有该登录名和电子邮件的用户是否存在。我在等待api抓取完成时遇到了一个问题,现在不知道如何链接它 行动Javascript React redux等待来自api的数据,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我正在使用react和redux与axios、thunk和promises中间件进行注册表单。首先,我想等待用户列表。然后,我想检查,如果不是post用户,则具有该登录名和电子邮件的用户是否存在。我在等待api抓取完成时遇到了一个问题,现在不知道如何链接它 行动 export function fetchUsers(){ return function(dispatch){ dispatch({type:"FETCH_USERS"}); axios.get(url)
export function fetchUsers(){
return function(dispatch){
dispatch({type:"FETCH_USERS"});
axios.get(url)
.then((response) => {
dispatch({type:"FETCH_USERS_FULLIFILED", payload: response.data});
})
.catch((err) => {
dispatch({type:"FETCH_USERS_ERROR", payload: err});
})
}
}
export function postUser(body){
return function(dispatch){
dispatch({type:"POST_USER"});
axios.post(url, body)
.then((response) => {
dispatch({type:"POST_USER_FULLFILED", payload: response.data});
})
.catch((err)=>{
dispatch({type:"POST_USER_ERROR", payload: err})
})
}
}
我想获取用户列表并检查用户何时单击提交按钮。我不能做那样的事情,因为没有then()
方法
this.props.dispatch( fetchUsers()).then(()=>{
//checking my conditions
// if all is ok
this.props.dispatch(postUser(body))
})
为什么不将
操作
与触发api
的方法分开呢
您可以将Promise
用于fetchUsers()
和postaser()
中,并且可以轻松地管理来自api函数的承诺。选中此项:
// Api promise function.
export function fetchUsers(){
return new Promise ((resolve, reject) => {
axios.get(url)
.then((response) => {
resolve(response.data);
}).catch((err) => {
reject(err);
})
})
}
// Api promise function.
export function postUser(body){
return new Promise ((resolve, reject) => {
axios.post(url, body)
.then((response) => {
resolve(response.data);
}).catch((err) => {
reject(err);
})
})
}
// Actions file.
// todo: integrate the next code into your action function.
let dispatch = this.props.dispatch;
dispatch({type:"FETCH_USERS"});
fetchUsers().then(allUsersFetched => {
dispatch({type:"FETCH_USERS_FULLIFILED", payload: allUsersFetched})
//checking your conditions
// if all is ok
dispatch({type:"POST_USER"});
postUser(body).then(user => {
dispatch({type:"POST_USER_FULLFILED", payload: user});
}).catch(err => {
dispatch({type:"POST_USER_ERROR", payload: err})
})
}).catch((err) => {
dispatch({type:"FETCH_USERS_ERROR", payload: err});
})
解决了我的问题,打开了我对新事物的视野。非常感谢。真的很有帮助。很高兴我能帮上忙。