【问题标题】:Store a state in a variable [closed]将状态存储在变量中[关闭]
【发布时间】:2021-08-26 09:02:22
【问题描述】:

我正在尝试更改变量中的一些元素,我将它与 useState 一起使用,我可以更改它。

我只是想知道这个问题的快速答案。

这是我的代码:

import React, { useState } from "react";
import { Bar } from "react-chartjs-2";

const BarChart = ({ title, label, changeLabels, changeDatas }) => {
  //////this is the states //////
  let data = {
    labels: changeLabels,
    datasets: [
      {
        label: label,
        data: changeDatas,
        backgroundColor: [
          "#a7def8e1",
          "#7ec5e4ec",
          "#21a8e2eb",
          "#579deeeb",
          "#3165d4eb",
          "#3a68e77f",
        ],
      },
    ],
  };

  return (
    <>
      <Bar
        data={data}
        options={{
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            title: {
              display: true,
              text: title,
              color: "#345fbb",
              font: { size: 22 },
            },
          },
        }}
      />
    </>
  );
};
export default BarChart;

我正在设置这个变量的状态。并在其他组件中使用 setState 和 useContext,

但是,我只是觉得出于某种原因这样做是不对的。顺便说一句,它没有任何错误。 可以这样用吗??

【问题讨论】:

  • 你没有状态,useState 永远不会被调用,你只是将一些道具传递给另一个组件。
  • 我认为您所说的“状态”与 React 状态的概念非常不同。看起来您只是将道具传递给子组件。我在这里没有看到任何明显的问题。
  • 我需要在这个问题上提供更多细节。我现在不在电脑上,所以我不能写更多的代码。我的意思是道具是来自另一个组件的useState的状态谢谢你的回答!

标签: reactjs


【解决方案1】:

这不是 React 状态,这是从 props 派生的对象,这绝对没问题。

你没有在内部改变任何道具或任何东西——你的方法没有错。

如果计算 data 对象更复杂,您可能需要使用 useMemo 挂钩,如下所示:

import React, { useState } from "react";
import { Bar } from "react-chartjs-2";

const BarChart = ({ title, label, changeLabels, changeDatas }) => {
  const data = React.useMemo(
    () => ({
      labels: changeLabels,
      datasets: [
        {
          label: label,
          data: changeDatas,
          backgroundColor: [
            "#a7def8e1",
            "#7ec5e4ec",
            "#21a8e2eb",
            "#579deeeb",
            "#3165d4eb",
            "#3a68e77f",
          ],
        },
      ],
    }),
    [changeLabels, changeDatas, label],
  );

  const options = React.useMemo(
    () => ({
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: title,
          color: "#345fbb",
          font: { size: 22 },
        },
      },
    }),
    [title],
  );

  return <Bar data={data} options={options} />;
};
export default BarChart;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2022-01-18
    • 2012-10-17
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多