reactjs - 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;
解决方案
我复制了您的代码并进行了一些更改以确保。问题出在你的减速器上。
function RootReducer(state = initialState, action) {
if(action.type === "REMOVE_NEWSITEMS"){
return Object.assign({}, state, {
newsItems: []
});
}
return state; // You need to return state
};
默认情况下,所有 reducer 在任何条件下都必须返回一个状态对象。即使它不适合任何情况或条件。在您的根减速器中,您需要返回状态。
推荐阅读
- google-workspace - 如何将 G Suite SDK 可见性从域更改为公开?
- appium - 单击 textView 上的特定文本
- sql-server - 外键引用无效表。无法创建约束或索引
- xcode - 代码设计抛出错误'errSecInternalComponent'
- java - Swing - 如何制作具有不透明内容的透明 JFrame?
- firebase - Google Firebase SSL 证书 - 我的证书列出了大量其他网站
- java - 运行 jar - JSONObject 抛出 IllegalArgumentException
- c# - 如何从 webresponse/streamreader 捕获数据并将其写回控制台?
- java - 在 Java 中覆盖树节点引用的问题
- typescript - TypeScript 递归条件映射类型