从React Redux调用后端



我有一个react-redux应用程序,它包含一个表示数据的表组件和一个通过下拉列表过滤数据的过滤器组件。我需要改变我的应用程序,这样我就可以接收数据的后端每次选择使用下拉菜单。我有以下内容:组件,reducer,动作创建者,mapStateToProps和mapDispatchToProps。我应该在哪里调用后端?

您可以使用redux中间件在您的操作中公开api客户端。

My redux中间件:

export default function clientMiddleware(client) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState);
    }
    const { promise, types, ...rest } = action; // eslint-disable-line no-redeclare
    if (!promise) {
      return next(action);
    }
    const [REQUEST, SUCCESS, FAILURE] = types;
    next({ ...rest, type: REQUEST });
    const { auth } = getState();
    client.setJwtToken(auth.token || null);
    const actionPromise = promise(client, dispatch);
    actionPromise.then(
      result => next({ ...rest, result, type: SUCCESS }),
      error => next({ ...rest, error, type: FAILURE })
    ).catch((error) => {
      console.error('MIDDLEWARE ERROR:', error);
      next({ ...rest, error, type: FAILURE });
    });
    return actionPromise;
  };
}

在动作中的用法:

const SAVE = 'redux-example/widgets/SAVE';
const SAVE_SUCCESS = 'redux-example/widgets/SAVE_SUCCESS';
const SAVE_FAIL = 'redux-example/widgets/SAVE_FAIL';
export function save(widget) {
  return {
    types: [SAVE, SAVE_SUCCESS, SAVE_FAIL],
    id: widget.id, // additionnal data for reducer
    promise: client => client.post('/widget/update', {
      data: widget
    })
  };
}
// in reducer:
export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case SAVE:
      return state;
    case SAVE_SUCCESS:
      // you can use action.result and action.id here
      return state;
    case SAVE_FAIL:
      // and you can use action.error and action.id here
      return state;
    default:
      return state;
  }
}

最后,你必须通过mapDispatchToProps将这个动作传递给你的组件。

希望对你有所帮助

我使用redux-api-middleware https://github.com/agraboso/redux-api-middleware基于Dan Abramov的例子

最新更新