【问题标题】:React redux using state within an action creator使用动作创建者中的状态反应 redux
【发布时间】:2020-03-02 08:18:30
【问题描述】:

我正在尝试使用曾经在我的组件逻辑中的方法创建一个动作创建器。我知道如何把它变成一个动作创造者;但是,我不确定如何解决三元运算符,因为它依赖于来自当地国家的东西。 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'));
    }
}

另外,有人可以根据您在动作创建器中看到的内容为我确认吗?有什么理由为这个动作创建者创建一个减速器吗?我似乎没有看到任何理由,因为它不用于改变状态,但我希望其他人对此有意见。谢谢

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案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'));
      }
    }
    

    【讨论】:

    • 是否有任何理由使用 getState 会被认为是不好的做法?
    猜你喜欢
    • 2016-06-10
    • 2018-09-02
    • 2017-05-21
    • 2018-10-04
    • 2016-09-16
    • 2017-09-16
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多