使用动作创建者中的状态来反应redux



我正试图用一个曾经在我的组件逻辑中的方法创建一个动作创建者。我知道如何把它变成一个动作创造者;然而,我不知道如何处理三元运算符,因为它依赖于来自局部状态的东西this.state.searchTerm以及this.state.data.currentPage是代码按照我需要的方式工作所必需的。

export const loadMoreMovies = () => {
return dispatch => {
const searchEndpoint = `${SEARCH_BASE_URL}${this.state.searchTerm}&page=${this.state.data.currentPage + 1}`;
const popularEndpoint = `${POPULAR_BASE_URL}&page=${this.state.data.currentPage + 1}`;
const endpoint = this.state.searchTerm ? searchEndpoint : popularEndpoint;
dispatch(fetchMovies(endpoint, 'search'));
}
}

此外,有人能从你在动作创作者身上看到的东西中为我确认吗?有什么理由为这个动作创建者创建一个减速器吗?我似乎看不出有任何理由这样做,因为它不用于改变状态,但我希望其他人对此有看法。感谢

使用redux-thunk时,从操作创建者返回的函数可以有两个参数,第二个参数是提供当前状态的函数:

export const loadMoreMovies = () => {
return (dispatch, getState) => {
const state = getState();
const searchEndpoint = `${SEARCH_BASE_URL}${state.searchTerm}&page=${state.data.currentPage + 1}`;
const popularEndpoint = `${POPULAR_BASE_URL}&page=${state.data.currentPage + 1}`;

const endpoint = state.searchTerm ? searchEndpoint : popularEndpoint;
dispatch(fetchMovies(endpoint, 'search'));
}
}

最新更新