Reactjs 如何在redux中将状态参数添加到异步操作?
我需要将和参数传递给异步操作。param是searchField值,它有一个单独的操作和缩减器。我需要传递参数,因为它是我正在进行的获取调用的URL的一部分。以下是actions、reduce和App.js文件中的代码: Actions.js:Reactjs 如何在redux中将状态参数添加到异步操作?,reactjs,redux,Reactjs,Redux,我需要将和参数传递给异步操作。param是searchField值,它有一个单独的操作和缩减器。我需要传递参数,因为它是我正在进行的获取调用的URL的一部分。以下是actions、reduce和App.js文件中的代码: Actions.js: export const setSearchField = text => { return { type: CHANGE_SEARCH_FIELD, payload: text }; }; export const re
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 }));
};
Reducers.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;
}
};
App.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")))
};
};
我需要传递到onrequestmein()
parameterssearchField
,该字段的状态来自另一个操作onSearchChange()
谢谢我不确定您是否在使用redux saga,但是,您应该能够将输入值与操作一起发送。 您应该发布您的代码,而不是pastebin:) 所以你的动作创造者看起来像
export const searchRequest=(术语)=>({
类型:搜索\请求\开始,
学期
});代码>
如果您有一个搜索\u请求\u启动操作,当然:)
然后从您的组件中,您可以发送如下内容
const search=(事件)=>{
分派(searchRequest(event.target.value));
};代码>
无论您是否使用saga,都应该通过action
在get函数或reducer中提供输入值
希望这有帮助。欢迎使用Stack Overflow:)请在post而不是PasteBin中添加文件。您需要使用redux thunk来处理异步操作