首页 > 解决方案 > 在Javascript中切片和映射数组但看不到切片数组出现

问题描述

我有一组保存的项目,我将它们传递到我的组件中。我的目标是让其中两个显示在页面顶部,旁边有一个“查看更多”按钮,单击该按钮时,将显示数组中的另一个项目,依此类推。

我正在使用 useState 挂钩来完成此操作,以及对已保存项目的数组进行切片和映射。

但是,我看不到任何数组元素出现在 DOM 中。

当我对数组进行console.log时,在控制台中可以看到整个数组,所以不觉得是props的问题。

我不确定从这里去哪里或确切的问题是什么。

import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getGames } from '../../actions/game';
import SingleGameMetrics from './SingleGameMetrics';

const FeaturedMetrics = ({ auth, getGames, game: { games } }) => {
  useEffect(() => {
    getGames();
  }, [getGames]);

  const [itemCount, setCount] = useState({
    itemCount: 2,
  });

  // Method
  const generateMoreMetrics = () => {
    setCount({
      itemCount: itemCount >= games.length ? itemCount : itemCount + 1,
    });
    console.log(games);
  };
  return (
    auth.isAuthenticated &&
    auth.loading === false && (
      <div>
        {games.slice(0, itemCount).map((game) => (
          <SingleGameMetrics key={game._id} game={game} />
        ))}
        <button onClick={(e) => generateMoreMetrics(e)}>View More +</button>
      </div>
    )
  );
};

FeaturedMetrics.propTypes = {
  auth: PropTypes.object.isRequired,
  getGames: PropTypes.func.isRequired,
  game: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  auth: state.auth,
  game: state.game,
});

export default connect(mapStateToProps, { getGames })(FeaturedMetrics);

它被传递到父组件中,如下所示:

<FeaturedMetrics />

这是否需要其他类似的东西

<FeaturedMetrics game={game} /> ?

标签: arraysreactjsdomsliceuse-state

解决方案


问题是我将 itemCount 作为初始 useState 挂钩中的对象,以及带有 {} 的 setCount 方法,而不仅仅是需要 ()。

不正确:

const [itemCount, setCount] = useState({
    2
  });

解决方案:

const [itemCount, setCount] = useState(
    2
  );

不正确:

setCount({
      itemCount + 1,
    });

解决方案:

setCount(
      itemCount + 1,
    );

推荐阅读