在反应中导出或发送数据

export or send data in react

如何将我的数据从 React 有状态组件导出到简单的 JS 文件?

例如: 从这里:(我想导出日期)

function Calendar() {
  const [selectedDay, setSelectedDay] = useState([
   {year: 2021, month:11, day:11},
   {year: 2022, month: 1, day: 2,
  ]);

  const dates = selectedDay.map(d => d)
}

这里是一个简单的js文件(builder.js):

(我想在 ..... 位置显示日期)

export const buildDaysCells = () => {
  const v = [];
  for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i += 1) {
    const startMonth = i;
    v.push({
      id: `m${startMonth}`,
      title: `${DAYS_NAMES[i]} ${......}`, 
    });
  }
  return v;
};

官方的回答是,“你不能”,reference。 您需要将这些代码更改为钩子:

function useCalendarDates() {
    const [selectedDay, setSelectedDay] = useState([
        { year: 2021, month: 11, day: 11 },
        { year: 2022, month: 1, day: 2 },
    ]);

    const dates = selectedDay.map(d => d);

    return dates;
}

export const useBuildDaysCells = () => {
    const dates = useCalendarDates();
    const v = [];
    for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i += 1) {
        const startMonth = i;
        v.push({
            id: `m${startMonth}`,
            title: `${DAYS_NAMES[i]} ${dates}`,
        });
    }
    return v;
};

您可以为 buildDaysCells 设置一个参数并将其传入 ...

export const buildDaysCells = (dates) => {
  const v = [];
  for (let i = 0; i < MONTHS_PER_YEAR * NUM_OF_YEARS; i += 1) {
    const startMonth = i;
    v.push({
      id: `m${startMonth}`,
      title: `${DAYS_NAMES[i]} ${dates}`, 
    });
  }
  return v;
};

然后在第一个组件中你可以传递日期

function Calendar() {
  const [selectedDay, setSelectedDay] = useState([
   {year: 2021, month:11, day:11},
   {year: 2022, month: 1, day: 2,
  ]);

  const dates = selectedDay.map(d => d)

  console.log(buildDaysCells(dates)) // You can check this part in your console
}

您可以通过从函数中获取数据来实现这一点,因为变量只会获取它们的数据,只有在反应组件中调用该函数的函数。 在数据文件中

import react, { useState } from "react";

function getData() {
  return [
    { year: 2021, month: 11, day: 11 },
    { year: 2022, month: 1, day: 2 },
  ];
}

function Calendar() {
  const [selectedDay, setSelectedDay] = useState(getData());

  const dates = selectedDay.map((d) => d);
}

export { Calendar, getData };

正在接收文件:

import React from "react";
import { getData } from "./result";

const App = () => {
  console.log(getData());
  return <div>{JSON.stringify(getData())}</div>;
};

export default App;