在 action creator 中使用 state 反应 redux
React redux using state within an action creator
我正在尝试使用一种曾经在我的组件逻辑中的方法来创建动作创建器。我知道如何把它变成一个动作创造者;但是,我不确定如何解决三元运算符,因为它依赖于来自本地状态的东西。 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
时,您 return 来自 action creator 的函数可以有两个参数,第二个参数是为您提供当前状态的函数:
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'));
}
}
我正在尝试使用一种曾经在我的组件逻辑中的方法来创建动作创建器。我知道如何把它变成一个动作创造者;但是,我不确定如何解决三元运算符,因为它依赖于来自本地状态的东西。 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
时,您 return 来自 action creator 的函数可以有两个参数,第二个参数是为您提供当前状态的函数:
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'));
}
}