首页 > 解决方案 > 如何将来自状态的参数添加到redux中的异步操作?

问题描述

我需要将参数传递给异步操作。参数是 searchField 值,它具有单独的操作和减速器。我需要传递参数,因为它是我正在执行的 fetch 调用的 URL 的一部分。以下是操作、reduce 和 App.js 文件中的代码:

Actions.js:

export const setSearchField = text => {
  return {
    type: CHANGE_SEARCH_FIELD,
    payload: text
  };
};

export const requestMeal = () => dispatch => {
  const url = `https://www.themealdb.com/api/json/v1/1/search.php?s=asd`
  dispatch({ type: REQUEST_MEAL_PENDING });
  fetch(url)
    .then(resp => resp.json())
    .then(data => {
      console.log(url);
      dispatch({ type: REQUEST_MEAL_SUCCESS, payload: data.meals });
    })
    .catch(err => dispatch({ type: REQUEST_MEAL_FAILED, payload: err }));
};

减速器.js:

const initalStateSearch = {
  searchField: ""
};

export const searchMeals = (state = initalStateSearch, action = {}) => {
  switch (action.type) {
    case CHANGE_SEARCH_FIELD:
      return Object.assign({}, state, { searchField: action.payload });
    default:
      return state;
  }
};
/////////

// reducer and initia; state for requestMeal action

const initalStateRequestMeal = {
  isPending: false,
  meals: [],
  error: ""
};

export const requestMeal = (state = initalStateRequestMeal, action = {}) => {
  switch (action.type) {
    case REQUEST_MEAL_PENDING:
      return Object.assign({}, state, { isPending: true });
    case REQUEST_MEAL_SUCCESS:
      return Object.assign({}, state, {
        isPending: false,
        meals: action.payload
      });
    case REQUEST_MEAL_FAILED:
      return Object.assign({}, state, {
        isPending: false,
        error: action.error
      });
    default:
      return state;
  }
};

应用程序.js

const mapStateToPros = state => {
  return {
    searchField: state.searchMeals.searchField,
    meals: state.requestMeal.meals,
    isPending: state.requestRandomMeal.isPending,
    error: state.requestRandomMeal.error,
    meal: state.requestViewMeal.meal
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onSearchChange: event => dispatch(setSearchField(event.target.value)),
    onRequestMeal: () => dispatch(requestMeal()),
    onRequestRandomMeal: () => dispatch(requestRandomMeal()),
    onRequestViewMeal: event =>
      dispatch(requestViewMeal(event.target.getAttribute("data-id")))
  };
};

我需要将来自其他动作的状态传递给onRequestMeal()参数。searchFieldonSearchChange()

谢谢

标签: reactjsredux

解决方案


不确定您是否使用 redux saga,但无论如何,您应该能够将输入的值与操作一起分派。你应该发布你的代码,而不是 pastebin :) 所以你的动作创建者看起来像

export const searchRequest = (term) => ({ type: SEARCH_REQUEST_START, term, });

当然,前提是您有SEARCH_REQUEST_START行动:)

然后从你的组件中你可以发送类似的东西

const search = (event) => { dispatch(searchRequest(event.target.value)); };

并且无论您是否使用 saga,您都应该在 get 函数或 reducer 中通过action

希望这可以帮助。欢迎来到堆栈溢出 :)


推荐阅读