首页 > 解决方案 > React/Redux:TypeError:无法读取未定义的属性

问题描述

我目前正在尝试在我的一个视图中实现 React/Redux 并遇到异常:

TypeError:无法读取未定义的属性“newsItems”

mapStateToProps在线函数出现错误newsItems: state.newsItems,

我的减速器初始化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));

减速器:

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;

标签: reactjsreduxreact-redux

解决方案


我复制了您的代码并进行了一些更改以确保。问题出在你的减速器上。

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

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

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


推荐阅读