使用动作创建者内的状态来响应redux

问题描述 投票:1回答:1

我正在尝试使用过去在组件逻辑内的方法来创建动作创建者。我了解如何将其转变为行动创造者;但是,我不确定如何解决三元运算符,因为它依赖于来自本地州的某些信息。代码需要this.state.searchTermthis.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'));
    }
}

而且,有人能从您在动作创建者中看到的内容为我确认吗?是否有任何理由为此动作创建者创建减速器?我似乎没有看到任何理由,因为它不是用来改变状态的,但我希望其他人对此表示赞同。谢谢

reactjs redux redux-thunk
1个回答
1
投票

[使用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'));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.