我有一个异步函数,可用于从API提取数据。在添加thunk之前它曾经可以正常工作,但是在使用thunk调用其他操作(例如[[start,成功和失败)之后,我开始收到const isLoadMore
未定义的错误,并且我不知道为什么。下面,我将在thunk之前包括working函数,并在添加redux-thunk之后包括not working函数。
正在工作
export const fetchMovies = async (endpoint, category) => {
const isLoadMore = endpoint.search('page');
let result;
try{
result = await (await fetch(endpoint)).json();
} catch(error){
// this.setState({error: true});
alert(error);
}
return{
type: HomeActionTypes.FETCH_MOVIES,
payload: {result, category, isLoadMore}
}
}
不工作
export const fetchMoviesStartAsync = (endpoint, category) => {
return async dispatch => {
dispatch(fetchMoviesStart());
const isLoadMore = endpoint.search('page');
let result;
try{
result = await (await fetch(endpoint)).json();
dispatch(fetchMoviesSuccess(result, category, isLoadMore));
} catch(error){
dispatch(fetchMoviesFailure());
alert(error);
}
}
}
应该发生的是,应该定义3个项目result
,category
和isLoadMore
,并准备将它们传递给成功动作创建者,以便减速器可以使用这些项目正确地更改状态。感谢您的帮助解决此问题。
export const fetchMoviesStartAsync = (endpoint, category) => {
return async (endpoint, dispatch) => {
dispatch(fetchMoviesStart());
const isLoadMore = endpoint.search('page');
let result;
try{
result = await (await fetch(endpoint)).json();
dispatch(fetchMoviesSuccess(result, category, isLoadMore));
} catch(error){
dispatch(fetchMoviesFailure());
alert(error);
}
}
}
我不确定它是否可以工作,但是他尝试。