【问题标题】:React redux waiting for data from apiReact redux 等待来自 api 的数据
【发布时间】:2018-01-04 21:09:24
【问题描述】:

我正在使用带有 axios、thunk 和 promises 中间件的 react 和 redux 进行注册表单。首先,我想等待用户列表。然后我想检查是否存在具有该登录名和电子邮件的用户,如果不是发布用户。我在等待 api 获取完成时遇到问题,现在真的不知道如何链接它。

动作

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))
})

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    为什么不将actions 与触发api 的方法分开呢?

    您可以在fetchUsers()postUser() 中使用Promise,您可以通过api 函数轻松管理promise。检查这个:

    // 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});
    })
    

    【讨论】:

    • 解决了我的问题,让我对新事物大开眼界。非常感谢,这真的很有帮助。
    • 很高兴我能帮上忙。
    • 有帮助!!已收藏!
    猜你喜欢
    • 2023-01-27
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2019-10-23
    相关资源
    最近更新 更多