为什么_.map只返回最后一项?

时间:2018-03-04 14:39:38

标签: reactjs react-redux lodash

我在我的状态下使用_.map进行映射,但它只返回最后一项。在控制台中,我看到数组存在于我的状态,但_.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 个答案:

答案 0 :(得分:0)

const mapStateToProps = state => { return {posts: state.posts}; }; 实际上根本没用。迭代是身份,在这种情况下,这导致不必要的计算。

其次你已经完成了这个const mapStateToProps = state => { return {posts: state}; }; 所以你的状态现在是这个的价值,这意味着而不是

{{1}}

你应该这样做

{{1}}