代码之家  ›  专栏  ›  技术社区  ›  ehsan

为什么会出现。是否仅返回最后一项?

  •  0
  • ehsan  · 技术社区  · 7 年前

    我正在使用 _.map ,但它只返回最后一项。在控制台中,我看到数组存在于我的状态,但 _.地图 仅返回其最后一项。

    //-------------this is my reducer------------------------
    const INITIAL_STATE = {};
    export const PostReducer = (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case FETCH_POSTS: {
          return _.mapKeys(action.payload.data);
        }
        default:
          return state;
      }
    };
    
    //----------this is my renderPost method ------------------------------
    
    renderPosts = () => {
        return _.map(this.props.posts, post => {
          return (
            <li className="list-group-item" key={post.id}>
              <h3>{post.title}</h3>
            </li>
          );
        });
      };
      
     //---------mapStateToProps------------------------------
     const mapStateToProps = state => {
      return {posts: state.posts};
    };
    export default connect(mapStateToProps, {fetchPosts})(PostsIndex);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    1 回复  |  直到 7 年前
        1
  •  0
  •   Akshat Gupta    7 年前

    _.mapKeys(action.payload.data) 实际上一点帮助都没有。迭代对象是标识,在这种情况下,这会导致不必要的计算。

    其次,你已经做到了 return _.mapKeys(action.payload.data); 所以你的状态现在是这个的值,这意味着

    const mapStateToProps = state => {
      return {posts: state.posts};
    };
    

    你应该这样做

    const mapStateToProps = state => {
      return {posts: state};
    };