javascript - 如何使用 React JS 根据条件使用数组对象
问题描述
我在其中使用反应功能组件,我有两个不同的数组对象。我想根据我拥有的条件渲染数组对象。我正在使用函数挂钩来定义引用并动态分配给它。但是,这是返回 null。有人可以帮我吗?在下面的代码中,渲染时isDemandGraph
返回。null
function gridHeatMap(props) {
const heatMap = [
{ color: 'redVeryHigh', value: 50 },
{ color: 'redHigh', value: 25 },
{ color: 'redMedium', value: 20 },
{ color: 'redLow', value: 15 },
{ color: 'white', value: 0 },
{ color: 'greenLow', value: 15 },
{ color: 'greenMedium', value: 20 },
{ color: 'greenHigh', value: 25 },
{ color: 'greenVeryHigh', value: 50 },
];
const demandHeatMap = heatMap.reverse();
const isDemandGraph = useRef(null);
const { height, title, viewName } = props;
const classes = useStyles();
return (
<div className={classes.root}>
<div className={classes.title}>{title}</div>
<Grid container spacing={0}>
{viewName === 'demand' ? { isDemandGraph: heatMap } : { isDemandGraph: demandHeatMap }}
{isDemandGraph.map((item, index) => {
return (
<Grid item style={{ flexGrow: '1', height, width: '11%' }} className={item.color}>
</Grid>
</Grid>
</div>
)
解决方案
我建议您使用useState
而不是useRef
使用useEffect
来监听道具更改,例如:
function gridHeatMap(props) {
const { height, title, viewName } = props;
const [isDemandGraph, setisDemandGraph] = useState([]);
const classes = useStyles();
const heatMap = [
{ color: 'redVeryHigh', value: 50 },
{ color: 'redHigh', value: 25 },
{ color: 'redMedium', value: 20 },
{ color: 'redLow', value: 15 },
{ color: 'white', value: 0 },
{ color: 'greenLow', value: 15 },
{ color: 'greenMedium', value: 20 },
{ color: 'greenHigh', value: 25 },
{ color: 'greenVeryHigh', value: 50 },
];
const demandHeatMap = heatMap.reverse();
useEffect(() => {
viewName === 'demand' ? setisDemandGraph(heatMap) : setisDemandGraph(demandHeatMap);
}, [viewName]);
return (
<div className={classes.root}>
<div className={classes.title}>{title}</div>
<Grid container spacing={0}>
{isDemandGraph.map((item, index) => {
return (
<Grid item style={{ flexGrow: '1', height, width: '11%' }} className={item.color}>
</Grid>
</div>
)
推荐阅读
- java - 为什么 Thymeleaf 找不到我的对象?
- java - Java 转换列表
列出 - python - 当省略 if 后的空格时,为什么 python3 内联 if 语句不会引发 SyntaxError?
- ssas - 在 SSAS 中创建 MDX 查询时从不同维度读取数据
- powershell - 查找字符串中任何一个数组元素的第一次出现 - Powershell
- python - 将文本保存到 docx 文件 python
- amazon-web-services - AWS ELB:503 服务暂时不可用
- python-3.x - Python - Selenium XPATH 查询不匹配
- php - postgresql 查询中的参数资源问题
- php - 用户密码重置功能