简体   繁体   中英

State Not Changing Properly In React Redux

I am new to React Redux I have initialized state which is properly displaying by calling its respective reducer which job to return the initialize State. But after mutating the state the state most probably not changing and i cant figure it out why

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
})

Your overall state shape will look like

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

after the very first reducer call. Is this what you want? Asking because you have

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

instead of just

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM