简体   繁体   English

如何在反应 state 中将元素推入数组,数组位于 object 内部

[英]How to push elements into array in react state, the array is located inside of object

Push object inside of questions array in data, it gives this errors Uncaught TypeError: data.sections is not iterable at handleClick (SecondStep.tsx:14:1)将 object 推入数据中的问题数组中,它会给出此错误 Uncaught TypeError: data.sections is not iterable at handleClick (SecondStep.tsx:14:1)

 export default function CreateStepper() { const [data, setData] = useState({ name: "", desc: "", sections: [], }); console.log(data); return ( <><SecondStep data={data} setData={setData} /></>) } function SecondStep(data: any, setData: any) { const [addSection, setAddSection] = useState(1); const newSection = { sectionName: "Hdsd", sectionDesc: "dsdsd", question: [], }; const handleClick = () => { setData({...data, sections: [...data.sections, newSection] }); }; return ( <Box> </Box> ); } export default SecondStep;

When I did below code it retuns "Uncaught TypeError: Cannot read properties of undefined (reading 'push')" this type error.当我执行下面的代码时,它会返回“Uncaught TypeError: Cannot read properties of undefined (reading 'push')”这个类型错误。 How to push new object to the array in React useState.如何将新的 object 推送到 React useState 中的数组。 First of all, useState is object inside the object it has questions: [] array how to push the object this array首先useState是object里面的object有疑问:【数组如何推入object这个数组】

 const [data, setData] = useState({ name: "", desc: "", sections: [], }); const newSection = { sectionName: "Hello", sectionDesc: "Desc", question: [], }; const handleClick = () => { let copyData = data; copyData.sections.push(newSection); setData(copyData); };

You can get the latest version of the state in the setState Method, where you then can add your object.您可以在 setState 方法中获取最新版本的 state,然后您可以在其中添加您的 object。

const [data, setData] = useState({
    name: "",
    desc: "",
    sections: [],
 });

const newSection = {
    sectionName: "Hello",
    sectionDesc: "Desc",
    question: [],
};

const handleClick = () => {
   setData(data => ({
     ...data,
     sections: [...data.sections, newSection]
   })
 };

But I am actually not quite sure if you need the ...data you might be able to leave that out.但我实际上不太确定您是否需要...data ,您可以将其排除在外。

You have to clone the object and then push the elements into the array,您必须克隆 object 然后将元素推送到数组中,

here is the example below,这是下面的示例,

import "./styles.css";
import React, {useState} from 'react'

export default function App() {

  const [data, setData] = useState({
    name: "",
    desc: "",
    sections: [],
 });

const newSection = {
    sectionName: "Hello",
    sectionDesc: "Desc",
    question: [],
};

const handleClick = () => {
   setData({...data, sections:[...data.sections, newSection]});
 };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={handleClick}>Click</button>
      <h4>Sections: {data.sections[0]?.sectionName}</h4>

    </div>
  );
}

Code Sandbox: https://codesandbox.io/s/react-do7bk?file=/src/App.js:0-572代码沙箱: https://codesandbox.io/s/react-do7bk?file=/src/App.js:0-572

The answer to you Updated Problem is:更新问题的答案是:

import "./styles.css";
import React, { useState } from "react";

export const CreateStepper = () => {
  const [data, setData] = useState({
    name: "",
    desc: "",
    sections: []
  });

  const SecondStep = (data: any) => {
    const [addSection, setAddSection] = useState(1);
    const newSection = {
      sectionName: "Hdsd",
      sectionDesc: "dsdsd",
      question: []
    };

    const handleClick = () => {
      setData({ ...data, sections: [...data.sections, newSection] });
    };

    return <></>;
  };

  return (
    <>
      <SecondStep data={data} />
    </>
  );
};

export default CreateStepper;

You could also provide SecondStep with the function via the Props If you prefer That this should work to:您还可以通过道具为 SecondStep 提供 function 如果您愿意,这应该可以:

export default function CreateStepper() {
  const [data, setData] = useState({
    name: "",
    desc: "",
    sections: [],
  });

  console.log(data);

  return (
    <><SecondStep data={data} setData={setData} /></>)
}


function SecondStep(data: any, setData: (data : any) => void) {
  const [addSection, setAddSection] = useState(1);
  const newSection = {
    sectionName: "Hdsd",
    sectionDesc: "dsdsd",
    question: [],
  };

  const handleClick = () => {
    props.setData({ ...data, sections: [...data.sections, newSection] });
  };

  return (
    <Box>
      
    </Box>
  );
}

export default SecondStep;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何推送元素以响应钩子状态数组 - How to push elements to react hooks state array (javascript)是否可以在位于另一个 object 内的阵列中推送 object? - (javascript)Is it possible to push an object in the array located inside another object? how to create an array of JSON objects, store them in a state array object and print the elements inside the render function in react-native - how to create an array of JSON objects , store them in a state array object and print the elements inside the render function in react-native 如何访问嵌套在 React 中的状态数组中的对象中的元素? - How to access elements in an Object which nested in an array of State in React? 如何使用 React 和 TypeScript 在嵌套数组中推送 object? - How to push an object inside nested array using React and TypeScript? 推送另一个数组中每个对象内的每个对象的元素 - push elements of each object inside each object inside another array 如何更改在 React 中作为状态传递的对象内的数组项值? - How to change an array item value inside an object passed as state in React? react中如何将json推送到Mobx的数组状态 - How to push the json to the array state of Mobx in react 如果项目位于javascript对象内,如何将其推入数组[state.lastValue.push不是函数] - how to push an item into an array if it is inside a javascript object [state.lastValue.push is not a function] 如果我在对象中有一个数组并且该对象在一个大数组中,我该如何更新 React Native 状态? - How can I update the React Native state if I have an array inside an object and the object is inside in a big array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM