状态在React Redux中未正确更改

时间:2019-04-30 18:18:33

标签: reactjs redux react-redux

我是React Redux的新手,我已经初始化了状态,可以通过调用其各自的reducer哪个作业来返回初始化状态来正确显示该状态。但是在改变状态之后,状态很可能不会改变,我无法弄清为什么

import { combineReducers } from 'redux';

const initialState = {
    songs:[
        {title:'No Scrubs', duration: '4:05'},
    ]
}

const songReducers = (state = initialState)=>{
    return state
}

const selectedSongReducer =(selectedSong=null,action)=>{
    if(action.type==='SONG_SELECTED'){
        return action.payload
    }

    return selectedSong;
}


const addSongReducer = (state=initialState,action)=>{
    if(action.type==="ADD_SONG"){
       return {
        ...state,   
        songs:[
           ...state.songs, {title:'All demo', duration: '4:05'}
        ]
    }
    }
    return state;
}

export default combineReducers({
    songs: songReducers,
    selectedSong: selectedSongReducer,
    addSong:addSongReducer
})

1 个答案:

答案 0 :(得分:1)

您的整体状态形状会像

state = {
    songs: {
        songs: [
            { title: 'No Scrubs', duration: '4:05' },
        ]
    },
    selectedSong: null,
    addSong: {
        songs: [
            { title: 'No Scrubs', duration: '4:05' },
        ]
    }
}

在第一个reducer调用之后。这是你想要的吗?因为有

而问
state = {
    songs: {
        songs: [
            { title: 'No Scrubs', duration: '4:05' },
        ]
    },
    ...
}

不只是

state = {
    songs: [
        { title: 'No Scrubs', duration: '4:05' },
    ]
    ...
}