我如何使用useState更新键名

问题描述 投票:0回答:1

React的Kinda新手:/所以我正在使用React chartjs渲染2组数据。它将首先加载dataWeekly,我有一个带有2个按钮onClick函数的下拉菜单,可在渲染dataWeekly和dataMonthly之间进行切换。我使用useState的方法是将dataWeekly和dataMonthly传递到{data}的正确方法吗?

const dataWeekly = {
    labels: labelsWeekly,
    datasets: [
      {
        label: 'Weekly sentiment over time',
        data: weeklyData,
        backgroundColor: palette.warning.light
      }
    ]
  };

  const [data, setData] = React.useState(dataWeekly);
    useEffect(() => {
      setData(dataWeekly)
    }, []);

  const dataMonthly = {
    labels: labelsMonthly,
    datasets: [
      {
        label: 'Monthly sentiment over time',
        data: monthlyData,
        backgroundColor: palette.primary.main
      }
    ]
  }

  const renderMonthly = () => {
    setData(dataMonthly)
  }

  const renderWeekly = () => {
    setData(dataWeekly)
  }

 <CardHeader
        action={
          <Select
          value={timeFilter}
          onChange={handleChange}
          >
            <MenuItem onClick={renderWeekly} value='Weekly'>
            Weekly
          </MenuItem>
            <MenuItem onClick={renderMonthly} value='Monthly'>Monthly</MenuItem>
        </Select>
        }
        title="Sentiments Graph"
      />
      <Divider />
      <CardContent>
        <div className={classes.chartContainer}>
          <Line
            data={data}
            options={options}
          />
        </div>
      </CardContent>

console.log(data) gives me this

我只是不确定为什么不每周/每月和标签数据都传递给{data}。

javascript reactjs chart.js
1个回答
0
投票

您可能想在没有大括号的情况下执行setState( dataWeekly )setState( dataMonthly )

{ dataWeekly }{ dataWeekly: dataWeekly }的简写:用一个键"dataWeekly"创建一个新对象,并将该键的值设置为变量dataWeekly。因此,您的data状态将类似于{dataWeekly: { labels: ..., datasets: ... }},我想您只希望它成为内部对象{ labels: ..., datasets: ... }

© www.soinside.com 2019 - 2024. All rights reserved.