简体   繁体   中英

update array of objects using useEffect in React Hooks

I have the following array that include objects using React , this array display the users fields data in a specific page.

What is the right way to update this component using useEffect , specifically the array on load of the page before data are rendered, to include:

new element to push in the array

(on load of the page)

userData.splice(3, 0,
        {
          key: "gender",
          label: "DFR",
        },
    );

Initial Array

  const userData = [
    {
      key: "first_name",
      label: "XYZ",
    },
    {
      key: "last_name",
      label: "XYYZ",
    },
    {
      key: "username",
      label: "ABC",
    },
    {
      key: "age",
      label: "ABCC",
    },
    {
      key: "nationality",
      label: "EDP",
    },
  ];

I have tried the following but for some reason it wont work:

  useEffect(() => {
    userData.splice(3, 0,
        {
          key: "gender",
          label: "DFR",
        },
    );
  }), [];

PS: As you can see, i don't intend to use push .

Maybe the better way is to use ES6 spread syntax.

useEffect(() => {
    userData = [...userData,{key: "gender",
          label: "DFR"}]
    );
  }), [];

Yes cause you just update directly in the variable userData. If you want React rerender you should use setState

    const [userData, setUserDate] = useState(initialData)
    
    useEffect(() => {
        setUserDate(userData.splice(3, 0,
            {
              key: "gender",
              label: "DFR",
            },
        ))
   }), [];

You don't need to use an effect for that(actually, on the contrary - you shouldn't ).

useEffect is a hook that gets called AFTER the initial rendering of the component.

In your case, you just simply need to generate a set of fields in the form of an array to be used for the component rendering. If those fields are static , not changing and are always the same for the given component , you just encapsulate them in a normal variable in the component itself and then you use them in the rendering. As simple as that.

In the other hand, if they're non-static and different instances of the same component can have a different set of fields - calculate them in the parent component and pass them down as props .

If, however, the fields can change dynamically throughout component's lifetime, you need to use state. Once again, you simply assign the calculated field set to the initial state and you're done.

In all of those cases, you'll get your fields ready before the render phase has happened.

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