reactjs - 如何将来自状态的参数添加到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()
参数。searchField
onSearchChange()
谢谢
解决方案
不确定您是否使用 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
希望这可以帮助。欢迎来到堆栈溢出 :)
推荐阅读
- c# - 由不同线程单独创建的对象仍然是共享的
- powershell - 访问哈希表不存在的属性在模块内外的行为不同
- reactjs - React-dates initialMonth 基于可用日期
- c# - 为什么 webjobs api 总是返回“已接受”状态而不是 200 Ok
- c# - ASP.Net Core - 如何向默认 Microsoft 标识结构添加新字段
- java - java静态地图不会在其他类中更新
- ios - 垂直翻转图像(Swift)
- python - 以特定方式对文件进行排序
- php - 如何使用 Google Indexing API 发送批处理请求
- rest - 通过 HTTPS 使用 CRM 365 本地 Web Api