如何异步/等待 Redux-thunk 操作



action.js

export function getLoginStatus() {
  return async(dispatch) => {
    let token = await getOAuthToken();
    let success = await verifyToken(token);
    if (success == true) {
      dispatch(loginStatus(success));
    } else {
      console.log("Success: False");
      console.log("Token mismatch");
    }
    return success;
  }
}

组件.js

  componentDidMount() {
    this.props.dispatch(splashAction.getLoginStatus())
      .then((success) => {
        if (success == true) {
          Actions.counter()
        } else {
          console.log("Login not successfull");
        }
     });
   }

但是,当我编写组件.js带有异步/等待的代码时,如下所示,我收到此错误:

Possible Unhandled Promise Rejection (id: 0): undefined is not a function (evaluating 'this.props.dispatch(splashAction.getLoginStatus())')

组件.js

  async componentDidMount() {
     let success = await this.props.dispatch(splashAction.getLoginStatus());
     if (success == true) {
       Actions.counter()
     } else {
       console.log("Login not successfull");
     }
   }

如何等待 getLoginStatus() 然后执行其余语句?使用 .then() 时一切正常。我怀疑我的异步/等待实现中缺少某些内容。试图弄清楚这一点。

承诺方法

export default function createUser(params) {
  const request = axios.post('http://www...', params);
  return (dispatch) => {
    function onSuccess(success) {
      dispatch({ type: CREATE_USER, payload: success });
      return success;
    }
    function onError(error) {
      dispatch({ type: ERROR_GENERATED, error });
      return error;
    }
    request.then(success => onSuccess, error => onError);
  };
}

异步/等待方法

export default function createUser(params) {  
  return async dispatch => {
    function onSuccess(success) {
      dispatch({ type: CREATE_USER, payload: success });
      return success;
    }
    function onError(error) {
      dispatch({ type: ERROR_GENERATED, error });
      return error;
    }
    try {
      const success = await axios.post('http://www...', params);
      return onSuccess(success);
    } catch (error) {
      return onError(error);
    }
  }
}

引用自 Medium 帖子,解释 Redux with async/await: https://medium.com/@kkomaz/react-to-async-await-553c43f243e2

重新混合 Aspen 的答案。

import axios from 'axios'
import * as types from './types'
export function fetchUsers () {
  return async dispatch => {
    try {
      const users = await axios
        .get(`https://jsonplaceholder.typicode.com/users`)
        .then(res => res.data)
      dispatch({
        type: types.FETCH_USERS,
        payload: users,
      })
    } catch (err) {
      dispatch({
        type: types.UPDATE_ERRORS,
        payload: [
          {
            code: 735,
            message: err.message,
          },
        ],
      })
    }
  }
}

 

import * as types from '../actions/types'
const initialErrorsState = []
export default (state = initialErrorsState, { type, payload }) => {
  switch (type) {
    case types.UPDATE_ERRORS:
      return payload.map(error => {
        return {
          code: error.code,
          message: error.message,
        }
      })
    default:
      return state
  }
}

这将允许您指定操作特有的错误数组。

另一个异步混音等待 redux/thunk。我只是发现在编写Thunk时这更易于维护和可读(a function that wraps an expression to delay its evaluation ~ redux-thunk )

操作.js

import axios from 'axios'
export const FETCHING_DATA = 'FETCHING_DATA'
export const SET_SOME_DATA = 'SET_SOME_DATA'
export const myAction = url => {
  return dispatch => {
    dispatch({
      type: FETCHING_DATA,
      fetching: true
    })
    getSomeAsyncData(dispatch, url)
  }
}
async function getSomeAsyncData(dispatch, url) {
  try {
    const data = await axios.get(url).then(res => res.data)
    dispatch({
      type: SET_SOME_DATA,
      data: data
    })
  } catch (err) {
    dispatch({
      type: SET_SOME_DATA,
      data: null
    })
  }
  dispatch({
    type: FETCHING_DATA,
    fetching: false
  })
}

减速器.js

import { FETCHING_DATA, SET_SOME_DATA } from './actions'
export const fetching = (state = null, action) => {
  switch (action.type) {
    case FETCHING_DATA:
      return action.fetching
    default:
      return state
  }
}
export const data = (state = null, action) => {
  switch (action.type) {
    case SET_SOME_DATA:
      return action.data
    default:
      return state
  }
}

可能未处理的承诺拒绝

似乎你错过了承诺.catch(error => {});。试试这个:

componentDidMount() {
    this.props.dispatch(splashAction.getLoginStatus())
        .then((success) => {
            if (success == true) {
                Actions.counter()
            } else {
                console.log("Login not successfull");
            }
        })
        .catch(err => {
            console.error(err.getMessage());
        }) ;
}
使用 dispatch(this.props.splashAction.getLoginStatus())

代替 this.props.dispatch(splashAction.getLoginStatus())

相关内容

  • 没有找到相关文章

最新更新