代码之家  ›  专栏  ›  技术社区  ›  Emm

添加CombineReducer后无法读取未定义(读取“map”)的属性

  •  0
  • Emm  · 技术社区  · 2 年前

    我组合了两个reducer函数,一个是返回电影列表,另一个是我正在构建的,用于处理用户将电影添加到“收藏夹列表”的逻辑。

    import { combineReducers } from 'redux';
    import movieReducer from './movieReducer';
    import movieFavReducer from './movieFavReducer';
    
    //combined reducers 
    export default combineReducers({ movieReducer, movieFavReducer });
    

    如果我不合并这两个减缩器,只合并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 问题是,这没什么,尽管当我不合并我的减缩器时,电影会被传下来。

    请帮我弄清楚

    1 回复  |  直到 2 年前
        1
  •  0
  •   Tércio Garcia    2 年前

    当你使用 combineReducers ,它不会合并减速器状态,而是创建一个嵌套了这些状态的新减速器。

    通过做 combineReducers({ movieReducer, movieFavReducer }) 你会得到这样的结果:

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

    也就是说,问题似乎在你的头上 mapStateToProps 实施 试试这个:

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

    更多关于 组合传感器 official docs .