"state.set is not a function" 作为我的 react-redux-immutable 学习曲线的一部分

"state.set is not a function" as part of my react-redux-immutable learning curve

动作创建器被调用了两次,它在第一种情况下工作正常,但在第二次调用时却没有按预期工作。 第一次。 这在第二次通话中一直发生。

在我设置它之前将状态写入控制台,得到那些有趣的细节,我不清楚我做错了什么

这是第一次出现的状态,在设置它之前 -

这是第二次调用时的状态 -

// The Action Creator
import config from "../../Config";
export const getLiveComments = () => {

    return (dispatch) => {
        fetchComments()
            .then(response => {
                if (!response.ok){
                    throw Error(response.statusText);
                }

                response.json().then(
                    comments => dispatch(gotComments(comments)))
            }
        ).catch(function(error) {
            console.log('There has been a problem with your fetch operation: ' + error.message);
        })
    };

};

function fetchComments(){
    return fetch(`${config.apiurl}/live-comments/get`, {
        method: 'GET',
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json'
            }
        })
}

function gotComments(comments){
    return {
        type: 'GOT_COMMENTS',
        comments:comments
    }
}


//The Reducer
import Immutable from 'immutable';
const initialState = Immutable.fromJS({
    comments: []
});

export default function (state = initialState, action) {
    switch (action.type) {
        case ("GOT_COMMENTS"):
            console.log('STATE (COMMENTS)', state)
            return state.set('comments', action.comments).toJS();
        default:
            return state;
    }
}

reducer-live-comments.js:10 Uncaught (in promise) TypeError: state.set is not a function at ./src/common/ChatMessages/reducer-live-comments.js.webpack_exports.a (reducer-live-comments.js:10) at combineReducers.js:39 at Array.forEach () at combineReducers.js:36 at Map.withMutations (immutable.js:1353) at combineReducers.js:35 at computeNextEntry (:2:27469) at recomputeStates (:2:27769) at :2:31382 at Object.dispatch (createStore.js:165) at dispatch (:2:31875) at index.js:14 at index.js:21 at dispatch (applyMiddleware.js:35) at get-live-comments.js:22 at

您返回的 .toJS() 不再是不可变对象。

return state.set('comments', action.comments).toJS();

下一次你的 reducer 运行时,状态将是一个普通的对象。

删除.toJS()

问题是你的减速器。

return state.set('comments', action.comments).toJS();

删除.toJS()

例如:const newState = state.setIn(['comments'], fromJS(action.comments))

更多信息here