¿Cómo puedo exportar mis datos de un componente con estado de reacción a un archivo JS simple?
por ejemplo: Desde aquí: (quiero exportar fechas)
function Calendar() { const [selectedDay, setSelectedDay] = useState([ {year: 2021, month:11, day:11}, {year: 2022, month: 1, day: 2, ]); const dates = selectedDay.map(d => d) }Aquí un archivo js simple ( builder.js ):
(Quiero mostrar fechas en ..... lugar)
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; };Puede establecer un parámetro para buildDaysCells y pasarlo en ...
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; };luego en el primer componente puedes pasar fechas
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 }La respuesta oficial es, "No puedes", referencia . Necesitas cambiar estos códigos en ganchos:
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; };Puede lograr esto obteniendo datos de la función, ya que la variable solo obtendrá sus datos, solo la función se llama a la función en el componente de reacción. en archivo de datos
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 };En el archivo de recepción:
import React from "react"; import { getData } from "./result"; const App = () => { console.log(getData()); return <div>{JSON.stringify(getData())}</div>; }; export default App;