如何在 redux react 应用程序中处理异步调用

How to handle asynchronous call in redux react application

我是 React 应用的初学者。我需要在我的应用程序中处理异步调用。

对于实现异步调用有没有相关的库?

如何使用库实现异步调用?

如果您使用的是 vanilla ReactJS,并且您的 App 不需要任何 Flux 或 Redux 来控制 App 的状态,您可以使用内置的 React 生命周期方法 componentWillMount fetch 方法或库,如 axios

如果您的应用程序需要 FluxRedux,那么我个人建议 Redux 而不是 Flux,您可以为此使用 redux-thunk 中间件。例如

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER
  };
}

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

有关更多信息,请参阅 http://redux.js.org/docs/advanced/AsyncActions.html

对于实现异步调用,您可以将以下库与 react-redux 结合使用

  1. redux-thunk
  2. redux-promise
  3. redux-saga

您可以使用库文档学习异步调用处理

这是有关如何使用异步操作的文档:http://redux.js.org/docs/advanced/AsyncActions.html

你在配置store的时候这样定义:

const store = createStore(
  rootReducer,
  applyMiddleware(
    thunkMiddleware
  )
)

然后你在这样的操作中使用它:

function fetchAction(data) {
  // Return a function, this function will be activated the the thunk middleware with dispatch as parameter
  return function (dispatch) {
    // Dispatch some action before fetch (like setting loading)
    dispatch(requestData(data));

    // return a promise of the fetch
    return fetch('yoururl')
      .then(response => response.json())
      .then(json =>
        // dispatch a new action when you get your data
        dispatch(receivedData(data,json))
      ).catch (e = > 
        // you can also dispatch an error
        dispatch(errorData(data,e));
      )

  }
}