添加 combineReducers 后无法读取未定义的属性(读取 'map')

Cannot read properties of undefined (reading 'map') after adding combineReducers

我组合了两个 reducer 函数,一个返回电影列表,另一个我正在构建以处理使用户能够将电影添加到 'favorites list'.

的逻辑
import { combineReducers } from 'redux';
import movieReducer from './movieReducer';
import movieFavReducer from './movieFavReducer';

//combined reducers 
export default combineReducers({ movieReducer, movieFavReducer });

如果我不组合这两个 reducer 而只有 movieReducer,我会得到我拥有的所有电影,但是,当我组合这两个时,我收到错误消息:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

这是相关代码:

import React from 'react';
import { connect } from 'react-redux';
import * as actionCreators from '../actions/movieActions';
import MovieListItem from './MovieListItem';
import MovieFooter from './MovieFooter';

const MovieList = (props)=> {
    const{ movies, favorites } = props
    // const movies = [];

    return (
        <div className="col">
            <table className="table table-striped table-hover">
                <thead>
                <tr>
                    <th>Title</th>
                    <th>Director</th>
                    <th>Genre</th>
                    <th>Metascore</th>
                    <th></th>
                </tr>
                </thead>

                <tbody>
                    {
                        props.movies.map(movie=><MovieListItem key={movie.id} movie={movie}/>)
                    }
                </tbody>
            </table>
            
            <MovieFooter totalMovies={movies.length}/>
        </div>
    );
}

//reaching into state and getting specific properties I want
const mapStateToProps = state => {
    return {
        movies: state.movies,
        favorites: state.movies
    }
}

export default connect(mapStateToProps, actionCreators) (MovieList);

我读过的解决方案建议我在映射之前先检查电影是否包含任何东西,所以有点像 movies?.map,问题是这什么都没有,尽管事实上电影在我时被传下来了不要组合我的减速器。

请帮我解决这个问题

当您使用 combineReducers 时,它不会合并 reducer 状态,而是创建一个嵌套了这些状态的新 reducer。

通过combineReducers({ movieReducer, movieFavReducer })你会得到这样的东西:

{
  "movieReducer": {
    "movies": []
  },
  "movieFavReducer": {
    "movies": []
  }
}

也就是说,问题似乎出在您的 mapStateToProps 实施上。 试试这个:

const mapStateToProps = state => {
    return {
        movies: state.movieReducer.movies,
        favorites: state.movieFavReducer.movies
    }
}

有关 combineReducers 用法的更多详细信息,请参见 official docs