“state.set不是一个函数”作为我的react-redux-immutable学习曲线的一部分

时间:2017-12-29 14:51:27

标签: reactjs redux immutable.js redux-thunk

动作创建者被调用两次,它在第一个案例中工作得很好但在第二个调用时没有按预期工作。 第一次。 第二次电话会一直发生这种情况。

在我设置之前将状态写入控制台,获取那些有趣的细节,这对我来说并不清楚我做错了什么

这是第一次出现的状态,在设定之前 - enter image description here

这是第二次通话似乎的状态 - enter image description here

// 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(在promise中)TypeError:state.set不是函数       at ./src/common/ChatMessages/reducer-live-comments.js.webpack_exports.a(reducecer-live-comments.js:10)       在combineReducers.js:39       在Array.forEach()       在combineReducers.js:36       在Map.withMutations(immutable.js:1353)       在combineReducers.js:35       在computeNextEntry(:2:27469)       在recomputeStates(:2:27769)       at:2:31382       at Object.dispatch(createStore.js:165)       在派遣(:2:31875)       在index.js:14       在index.js:21       在发货时(applyMiddleware.js:35)       在get-live-comments.js:22       在

2 个答案:

答案 0 :(得分:1)

你正在返回.toJS(),它不再是一个不可变对象。

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

下次你的reducer运行时,state将是一个vanilla对象。

删除.toJS()

答案 1 :(得分:1)

问题是你的减速机。

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

删除.toJS()

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

更多信息here