我目前正在尝试在其中一种视图中实现React / Redux并遇到异常:
TypeError:无法读取未定义的属性“ newsItems”
在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));
减速器:
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;
我发现的大多数其他类似问题是由于初始状态未初始化为非null值,但是我正在提供初始值(空数组)
编辑: 我的redux商店看起来如下:
import { createStore } from "redux";
import RootReducer from "./reducers/RootReducer";
const store = createStore(RootReducer);
export default store;
答案 0 :(得分:1)
为确保复制,我对您的代码进行了一些更改。问题出在您的减速器上。
function RootReducer(state = initialState, action) {
if(action.type === "REMOVE_NEWSITEMS"){
return Object.assign({}, state, {
newsItems: []
});
}
return state; // You need to return state
};
默认情况下,所有reducer都必须在任何情况下返回状态对象。即使不适合任何情况或条件。在根减速器中,您需要返回状态。