【问题标题】:TypeError: Cannot read property 'map' of undefined react redux when updating类型错误:更新时无法读取未定义反应 redux 的属性“地图”
【发布时间】:2018-08-20 22:30:40
【问题描述】:

我正在更新一个帖子,然后当我点击更新时出现此错误

TypeError: Cannot read property 'map' of undefined..

这是我的减速器,有效载荷是

action.payload: {id: 1, title: "test", body: "update"}

case UPDATE_POST:

    const updatedItems = state.items.map(item => {
        if(item.id === action.payload.id){
            return { ...item, ...action.payload }
        }
        return item
    })
    return updatedItems

这是我的后期组件渲染

const postItems = this.props.posts.map(post => (
     <div key={post.id} className="row">
         <div className="container">
             <h3>{post.title}</h3>
              <p>{post.body}</p>
              <button
                  onClick={() =>this.editPost(post)}
                  className="btn btn-primary">
                  Edit
              </button>&nbsp;
              <button
                  onClick={() =>this.deletePost(post.id)}
                  className="btn btn-danger">
                  Delete
              </button>
          </div>
      </div>  
  ))

【问题讨论】:

标签: reactjs redux react-redux


【解决方案1】:

您正在使用state.items 访问数组,这意味着数组是对象的一部分,键是项目。所以最后你需要返回一个包含更新项目的对象,但你从reducer返回一个数组。

这样写:

case UPDATE_POST:

    const updatedItems = state.items.map(item => {
        if(item.id === action.payload.id){
            return { ...item, ...action.payload }
        }
        return item
    })

    return {...state, items: updatedItems }

【讨论】:

    【解决方案2】:

    首先检查Props中的数据是否到来,然后使用它。并在渲染中使用控制台对其进行调试,以检查数据是否到来。如果数据即将到来,那么它应该可以工作。如果仍然面临问题,请告诉我 您的问题与question 类似

    this.props.posts ?
    const postItems = this.props.posts.map(post => (
         <div key={post.id} className="row">
             <div className="container">
                 <h3>{post.title}</h3>
                  <p>{post.body}</p>
                  <button
                      onClick={() =>this.editPost(post)}
                      className="btn btn-primary">
                      Edit
                  </button>&nbsp;
                  <button
                      onClick={() =>this.deletePost(post.id)}
                      className="btn btn-danger">
                      Delete
                  </button>
              </div>
          </div>  
      ))
    : null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-26
      • 2019-12-07
      • 2021-05-22
      • 2020-05-27
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多