【问题标题】:Why does _.map only return the last item?为什么 _.map 只返回最后一项?
【发布时间】:2018-03-04 14:39:38
【问题描述】:

我在我的状态下使用_.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>

【问题讨论】:

  • 为什么不用原生的数组映射方式?
  • @evolutionxbox 因为他正在迭代一个对象。很难说posts 实际包含什么,因为我们不知道原始数据,但很可能_.mapKeys 不会生成正确的数据。
  • @Sulthan 我想知道Object.keys(myObj).map 会不会更好?
  • @evolutionxbox 他​​可能想在reducer中生成一个数组,然后使用map。在render 中的对象上map 没有意义,因为顺序可以更改。

标签: reactjs react-redux lodash


【解决方案1】:

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

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

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

你应该这样做

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

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多