简体   繁体   中英

Array of arrays using React useState

Why is it that this works:

let [thisState, setThisState] = useState([['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd']]);

works, but this doesn't

let [thisState, setThisState] = useState([])
setThisState([['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd']])

They're getting the same value input, but setThisState() really doesn't like the array of Arrays.

Sorry for not posting my initial code beforehand. I'm using a Component to render in a calendar, fromServerToLocal takes what exists in the database to a format the Calendar component can use.

import styles from '../../styles/Home.module.scss'
import Head from 'next/head'
import { Calendar, momentLocalizer } from 'react-big-calendar'
import moment from 'moment'
import withDragAndDrop from "react-big-calendar/lib/addons/dragAndDrop/withDragAndDrop"
import "react-big-calendar/lib/addons/dragAndDrop/styles.css"
import 'react-big-calendar/lib/css/react-big-calendar.css'
import React, { useEffect, useState } from 'react'




const localizer = momentLocalizer(moment)
const DnDCalendar = withDragAndDrop(Calendar)
export default function calendar() {
  let [serverEventList, setServerEventList] = useState([])

  useEffect(() => {


    async function go() {
      const res = await fetch('/api/endPoint', {
        headers: {
          'Content-Type': 'application/json',
        },
        method: 'GET'
      })

      let response = await res.json();

      return await response
    }
    go().then(x => {
      console.log(x);
      setServerEventList({ data: x })
    })



  }, [])

  function fromServerToLocal(serverObject) {
    let finishedArray = [];
    serverObject.forEach((entry, index) => {

      finishedArray.push({

        start: entry.startDate,
        end: entry.endDate,
        title: entry.firstName + " " + entry.lastName,
        resourceId: index
      })
    })

    return finishedArray;
  }
  function translateData(arrayOfObjects) {
    let properArray = []
    arrayOfObjects.forEach((entry) => {
      properArray.push({
        start: entry[0],
        end: entry[1],
        title: entry[2],
        resourceId: entry[3]
      })
    })
    console.log(`this: ${properArray}`)

    return properArray
  }
  return (

    <div className={styles.container}>

      <h1>Calendar</h1>
      <Head>
        <title>Calendar</title>
        <meta name="description" content="Rent a bike" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <DnDCalendar
        defaultDate={moment().toDate()}
        defaultView="month"
        localizer={localizer}
        events={fromServerToLocal(serverEventList)}
        resizable
        style={{ height: 500 }}
      />
      <p>    event: {serverEventList}</p>
    </div>
  )
}

You can also try to organize it a little bit like this:

    const initialState = [['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd']];

    let [thisState, setThisState] = useState(initialState);

to improve readability and to make sure there are no typos on the declaration of the initial state, I hope it helps.

Your code should work as-is. To verify you can log the changed state inside useEffect . You'll see the updated value.

let [thisState, setThisState] = useState([])
useEffect(() => {
    setThisState([['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd'],['a', 'b', 'c', 'd']])
}, [])
useEffect(() => console.log(thisState), [thisState]);

Try using setServerEventList({data: x})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM