【问题标题】:Redux Toolkit Slice Reducer not working when adding non-extra Reducer添加非额外 Reducer 时 Redux Toolkit Slice Reducer 不起作用
【发布时间】:2021-03-03 00:51:18
【问题描述】:

我是 Redux 的新手,从一开始就尝试使用 RTK,到目前为止,这对我来说是一个令人困惑的挑战。

现在我试图在我的切片中添加一个普通的 Reducer 而不是一个 extraReducer,我得到了我无法理解的奇怪结果。当我完全删除减速器声明时,一切都按预期工作。帖子被加载到道具中。

var initialState = { entities: [], ids: [], fetchState: "idle", current: 0 };

export const postSlice = createSlice({
    name: "posts",
    initialState: initialState,
    reducers: {
        currentPostChanged: (state, action) => {},
    },
    extraReducers: {
        [fetchAll.pending]: (state, action) => {
            state.fetchState = "pending";
        },
        [fetchAll.rejected]: (state, action) => {
            state.fetchState = "rejected";
        },
        [fetchAll.fulfilled]: (state, action) => {
            var keys = objectFlip(Object.keys(action.payload.entities.posts));
            var posts = Object.values(action.payload.entities.posts);
            state.entities = posts;
            state.ids = keys;
            state.fetchState = "idle";
        },
    },
});
export const postReducer = postSlice.reducer;

存储配置

var storeConfig = {
    reducer: {
        posts: postReducer,
    },
    middleware: [...getDefaultMiddleware()],
    devTools: process.env.NODE_ENV !== "production",
};

const store = configureStore(storeConfig);

映射状态

function mapStateToProps(state) {
    console.log(state);
    return {
        posts: state.posts.entities,
        postsIds: state.posts.ids,
    };
}

获取完成前的输出

posts: {…}
  entities: Object {}
  ids: Array []

提取完成后的输出

posts: {…}
  entities: Array(28) [ {…}, {…}, {…}, … ]
  fetchState: "idle"
  ids: Object { 2: "0", 3: "1", 4: "2", … }

React 组件中的渲染方法

render() {
    if (this.props !== undefined) {
        console.log("Component.render()");
        console.log(this.props);
    } 

    return <div></div>
}

输出

【问题讨论】:

    标签: javascript reactjs redux redux-thunk redux-toolkit


    【解决方案1】:

    问题是,我偶然在 mapDispatchToProps 中使用了相同的 props 变量 (props.post)。

    function mapStateToProps(state) {
        console.log(state);
        return {
            posts: state.posts.entities, // <-- declared here
            postsIds: state.posts.ids,
        };
    }
    
    
    const mapDispatchToProps = {
        addPosts: postsLoaded,
        fetchPosts: fetchAll,
        // posts: postSlice.actions.currentPostChanged, <-- and here
        // changed to
        changeCurrentPost: postSlice.action.currentPostChanged,
    };
    

    更改 mapDispatchToProps 中的键后一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 2023-03-03
      • 2016-06-23
      • 2021-01-24
      • 2017-11-03
      相关资源
      最近更新 更多