开发者问题收集

React/Redux:TypeError:无法读取未定义的属性

2019-02-28
7587

我目前正在尝试在我的某个视图中实现 React/Redux,但出现了异常:

TypeError: Cannot read property 'newsItems' of undefined

错误发生在 mapStateToProps 函数的 newsItems: state.newsItems, 行上

我的 Reducer 将 newsItems 初始化为一个空数组,因此我不确定为什么它会是 undefined

我的组件如下所示:

class PublicLayout extends Component {
  displayName = PublicLayout.name

  constructor(props) {
    super(props);
  }

  retrieveNewsItemsAndArticles = (newsType) => {
    //this method populates the articles and newsitems in the store.
  };

  updateNewsItems = (newsType) => {
    this.retrieveNewsItemsAndArticles(newsType);
  }

  render() {
      if(this.props.articles == null || this.props.newsItems == null){
        this.retrieveNewsItemsAndArticles(0);
      }
      else{
          if(initialLoad){
              initialLoad = false;
          }
      }

    let contents = this.props.articles == null || this.props.newsItems == null ? (
      <p>
          <em>Loading...</em>
      </p>
      ) : (
        this.renderContents()
      );

    return (
      <div className="container">  
        <PageHeader />
        <NavBar onSelectNewsType={this.updateNewsItems}/>

        {contents}
      </div>
    );
  }

  renderContents = () => {
    return (
      <div>
        <div>
          <HorizontalArticleBar />
        </div>
        <div className="row">
          <div className="col-lg-7">
            {this.props.children}
          </div>
          <div className="col-lg-5">
            <VerticalNewsItemBar />
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = function(state) {
  return {
    newsItems: state.newsItems,
    articles: state.articles
  }
}

export default withApollo(connect(mapStateToProps)(PublicLayout));

Reducer:

const initialState = {
  articles: [],
  newsItems: []
};

function RootReducer(state = initialState, action) {
  if(action.type === "REMOVE_NEWSITEMS"){
      return Object.assign({}, state, {
          newsItems: []
      });
  }
  //more here but never setting newsItems to null
};

export default RootReducer;

我发现的大多数其他类似问题是由于初始状态未初始化为非空值,但我提供了一个初始值(空数组)

编辑:我的 Redux 存储如下所示:

import { createStore } from "redux";
import RootReducer from "./reducers/RootReducer";

const store = createStore(RootReducer);

export default store;
1个回答

我复制了您的代码,并进行了一些更改以确保万无一失。问题出在您的 Reducer 中。

function RootReducer(state = initialState, action) {
  if(action.type === "REMOVE_NEWSITEMS"){
      return Object.assign({}, state, {
          newsItems: []
      });
  }

  return state; // You need to return state
};

默认情况下,所有 Reducer 在任何条件下都必须返回状态对象。即使它不适合任何情况或条件。在您的根 Reducer 中,您需要返回状态。

sdkcy
2019-03-01