【问题标题】:Redux reducer returns undefined error even it is initialized as nullRedux reducer 即使初始化为 null 也会返回未定义的错误
【发布时间】:2021-07-02 23:09:40
【问题描述】:

我的 Redux 减速器有问题。在 selectedSongReducer 中 selectedSong 被定义为 null 因此它不会返回错误,但我仍然收到以下错误:错误:Reducer "selectedSong" 在初始化期间返回未定义。如果传递给 reducer 的状态未定义,则必须显式返回初始状态。初始状态可能不是未定义的。如果不想给这个reducer设置值,可以用null代替undefined。

这里是reducer代码:

import { combineReducers } from 'redux';

const songsReducer = () => {
    return [
        { title: 'A' , length: '4:05' },
        { title: 'B' , length: '2:30' },
        { title: 'C' , length: '3:15' },
        { title: 'D' , length: '1:45' },
    ]
};

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

export default combineReducers({
    songs: songsReducer,
    selectedSong: selectedSongReducer
})

任何人对可能出现问题的地方有任何建议吗?

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您不小心使用了赋值运算符而不是在此处比较值 如果(action.type = 'SONG_SELECTED')。它总是会被执行。

    【讨论】:

    • 我不敢相信我没有看到。非常感谢您指出这一点。
    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 2017-09-04
    • 2016-05-05
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多