【问题标题】:Calling Backend from React Redux从 React Redux 调用后端
【发布时间】:2023-04-03 22:15:01
【问题描述】:

我有一个 react-redux 应用程序,其中包含一个显示数据的表格组件和一个通过下拉列表过滤数据的过滤器组件。我需要更改我的应用程序,以便每次使用下拉菜单进行选择时,我都可以从后端接收数据。我有以下内容:组件、reducers、action creators、mapStateToProps 和 mapDispatchToProps。我应该在哪里调用后端?

【问题讨论】:

  • 您可以从您的action creators 或component 本身调用它.. 或您能想到的任何其他方法/位置。我不建议从reducers 调用它、mapStateToProps 或 mapDispatchToProps
  • 看看 redux-thunk 库。它将做的,是允许您编写返回函数的动作创建者,并且在调用这些动作创建者时,它还将调用该函数并传递 redux 调度方法。然后,您可以使用 mapDispatchToProps 中间件,通过道具传递这些动作创建者,您可以从您的组件中调用它们。然后,您可以对检索事件进行操作,该操作可以在您对后端的请求的回调中分派。然后,Reducer 将处理将该操作中的数据放入存储中,并且当 props 更新时,您已经更新了组件中的数据。

标签: reactjs redux react-redux


【解决方案1】:

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

我的 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 将此操作传递给您的组件。

希望对你有所帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2019-03-21
      • 2019-02-20
      相关资源
      最近更新 更多