arrays - 在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} /> ?
解决方案
问题是我将 itemCount 作为初始 useState 挂钩中的对象,以及带有 {} 的 setCount 方法,而不仅仅是需要 ()。
不正确:
const [itemCount, setCount] = useState({
2
});
解决方案:
const [itemCount, setCount] = useState(
2
);
不正确:
setCount({
itemCount + 1,
});
解决方案:
setCount(
itemCount + 1,
);
推荐阅读
- javascript - Jquery 验证器移动输入字段
- javascript - javascript私有方法中的符号和弱映射有什么区别?
- mysql - TypeORM - 如何在生产模式下创建新表并自动运行迁移?
- python - Python字符串被多个分隔符分割
- include - 我可以使用 \input{file.tex} 或类似方法将 LaTeX 文件中的内容(不是整个文档)有效地带入 Jupyter 笔记本吗?
- php - 仅在使用静态方法时,如何在 Symfony 中修复“您是否忘记了“使用”语句 [...]?
- html - 为什么图片不会出现在 WordPress 网站的版权部分?
- r - 如何重复计算许多单列并将输出存储在 R 的新数据框中?
- c - 使用while循环连接两个数组
- api - 部署到服务器时反应被 CORS 策略阻止的 axios 请求