首页 > 解决方案 > 如何使用 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>
)

标签: javascriptreactjsreact-hooks

解决方案


我建议您使用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>
)

推荐阅读