我试图在我的组件中显示一个文章列表,在我的"articleList.js“组件上我得到了”无法读取属性‘映射’的未定义的“错误。我的代码有什么问题?而且当我记录文章的时候,它是没有定义的。
我的减速机里有下面的代码:
const initialState = {
articles: [],
loading: false,
error: null
};
export default (state=initialState, action) => {
switch (action.type) {
case GET_ARTICLES:
return {
...state,
articles: action.payload,
loading: false
};行动守则:
export const getArticles =()=> dispatch =>{
fetch('http://localhost:8000/api/articles/')
.then(handleErrors)
.then(res => dispatch(
{
type : GET_ARTICLES,
payload: res.json
}
))}组件代码:
componentDidMount() {
this.props.getArticles();
}
render() {
const { articles } = this.props.article;
return (
<div>
<div>
<div>
{articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))}
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
article: state.article
});
export default connect(
mapStateToProps, { getArticles} )(ArticleList);很抱歉抛出了大量的代码,它只是相关的,我相信错误就在一个未定义的initialState中,但是我看不出我错过了什么定义。
发布于 2018-11-24 07:22:41
似乎你把自己和单数/复数变量的名字搞混了。您的操作将articles设置为减速器状态中的复数:
return {
...state,
articles: action.payload,所以当你mapStateToProps
const mapStateToProps = state => ({
article: state.article
});state.article将是未定义的作为还原器,永远不会将其设置为奇异变量。另外,从您提供的片段中可以看出,无论如何我没有理由使用单数术语。
因此,试着改变如下:
const { articles } = this.props.articles;
const mapStateToProps = state => ({
articles: state.articles
});发布于 2018-11-24 07:17:10
好的,我认为您只需要检查您的文章是否未定义,状态更新可能是异步的,所以在第一次调用呈现方法时它是未定义的,只需执行以下操作
{articles ? {articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))} : null }https://stackoverflow.com/questions/53455881
复制相似问题