mapStateToProps不提供来自状态的数据

By simon at 2018-02-28 • 0人收藏 • 39人看过

我有这个错误:

TypeError:无法读取未定义的属性'map' 并且不知道this.props.movi​​es怎样才能被定义而我有 initialState声明为_ [] _然后它必须直接进行渲染? 所以有文件: Reducer.js

import * as types from "./ActionTypes.js";

const initialState = { movies: [] };

export const reducer = (state = initialState, action) => {
  console.log(state.movies);
  switch (action.type) {
    case types.GET_MOVIES:
      return {
        ...state,
        movies: action.value
      };
    default:
      return state;
  }
};
Movies.js
import React, { Component } from "react";
import { connect } from "react-redux";
import MovieItem from "./MovieItem";

const mapStateToProps = state => ({
  movies: state.movies
});

class Movies extends Component {
  render() {
    let movieItems = this.props.movies.map(movie => {
      return <MovieItem movie={movie} />;
    });
    return <div className="Movies">{movieItems}</div>;
  }
}

export default connect(mapStateToProps, null)(Movies);
即使我把if语句像
if (this.props.movies){
...
}else return 1;
它永不退缩

2 个回复 | 最后更新于 2018-02-28
2018-02-28   #1

它应该是:

const mapStateToProps = state => ({
    movies: state.reducer.movies
});
因为你的初始状态是一个对象:
initialState = { movies: [] };
你正在使用combineReducers像这样:
const rootReducer = combineReducers({ reducer: reducer }); 
现在所有减速器的initialState都可以通过
const rootReducer = combineReducers({ reducer: reducer }); 
4访问。 注意:而不是使用reducer,better使用一些直观的名字 像moviesReducer.稍后在将来如果你将添加更多的减速器,那么它会 有助于识别数据。

2018-02-28   #2

它应该是:

const mapStateToProps = state => ({
    movies: state.reducer.movies
});
因为你的初始状态是一个对象:
initialState = { movies: [] };
你正在使用combineReducers像这样:
const rootReducer = combineReducers({ reducer: reducer }); 
现在所有减速器的initialState都可以通过
const rootReducer = combineReducers({ reducer: reducer }); 
4访问。 注意:而不是使用reducer,better使用一些直观的名字 像moviesReducer.稍后在将来如果你将添加更多的减速器,那么它会 有助于识别数据。

登录后方可回帖

Loading...