【问题标题】:State Not Changing Properly In React ReduxReact Redux 中的状态未正确更改
【发布时间】:2019-04-30 18:18:33
【问题描述】:

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

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案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' },
        ]
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多