简体   繁体   中英

How to set or update state of Array in grand child component

I'm trying to set state of array from grand child component which is located in parent component.

I tried to use setNumberOfVar([...varsLines]); this method but it's not updating the state immediately.it updates but one step back.

My Code


  const removeVar = (e, val) => {
    e.preventDefault();
    var varsLines = numberOfVar;
    varsLines = numberOfVar.filter((item) => {
      return item.postion != val;
    });
    varsLines = varsLines.map((item) => {
      return {
        ...item,
        postion: item.postion > val ? item.postion - 1 : item.postion,
      };
    });
    console.log(varsLines);
    setNumberOfVar([...varsLines]); // <== this line is not updating the state immediately;
    console.log(numberOfVar);
  };

setNumberOfVar() is an async operation and will not update state immediately.

If you want to get something like a callback when the state is updated, you can use the useEffect hook that runs on state update.

import {useEffect } from 'react';

  useEffect(() => {
    console.log(numberOfVar);
  },[numberOfVar]); 

try to do something like this

setNumberOfVar(prevState=>prevState.filter().map())

use your own conditions in filter and map and see if it's working or not.

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