代码之家  ›  专栏  ›  技术社区  ›  Maryam Ghafarinia

无法读取未定义的属性“map”-react,redux

  •  2
  • Maryam Ghafarinia  · 技术社区  · 6 年前

    我试图在我的组件中显示文章列表,我的“ArticleList.js”组件中出现“cannot read property‘map’of undefined”错误。我的代码怎么了? 而且当我写文章时,它是未定义的。

    我的减速器中有以下代码:

     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);
    

    抱歉,大量的代码被丢弃了,这一切都是相关的,我相信错误就在有未定义的首字母的地方,但是我看不出我遗漏了定义什么。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Julius Dzidzevičius    6 年前

    似乎你把自己和单数/复数变量的名字混淆了。你的动作集 articles 在减速器状态下为复数:

    return {
      ...state,
      articles: action.payload,
    

    所以当你 mapStateToProps 以下内容:

     const mapStateToProps = state => ({
          article: state.article
      });
    

    state.article 未定义 因为reducer从不将其设置为奇异变量。另外,从你提供的片段中,我看不出有任何理由使用单数术语。

    所以尝试改变如下:

      const { articles } = this.props.articles;
    
      const mapStateToProps = state => ({
        articles: state.articles
      });
    
        2
  •  0
  •   Zaidoune Maher    6 年前

    好吧,我认为您只需要检查您的文章是否未定义,状态更新可能是异步的,所以在第一次调用render方法时,它是未定义的,只需执行如下操作

    {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 }