简体   繁体   中英

How to use function parameter inside useEffect hook

I have click event listener and I'm receiving data parameter in it. Inside of this function, I'm setting the state. Now I'm trying to change state based on the current state and I need useEffect to achieve that. But I don't know how to use function data parameter inside of it. Here's the code:

import React from 'react';

const MyApp = () => {
   const [state, setState] = React.useState([]);
   const arr1 = [
      {id: 1, name: 'Daryl'},
      {id: 2, name: 'Negan'},
   ];

   const clickHandler = (data) => {
       const newData = arr1.filter(item => item.name === data.name); // some data i wan't to use in useEffect
       setState(newData);
   };

   React.useEffect(() => {
       if(state.indexOf(newData[0]) !== -1) { // how to use this here?
           //rest of the code
       }
   }, [state]);
}

you don't need to use newData directly because you are setting its value into state

just change your component this way:

import React from 'react';

const MyApp = () => {
   const [state, setState] = React.useState([]);
   const arr1 = [
      {id: 1, name: 'Daryl'},
      {id: 2, name: 'Negan'},
   ];

   const clickHandler = (data) => {
       const newData = arr1.filter(item => item.name === data.name); // some data i wan't to use in useEffect
       setState(newData);
   };

   React.useEffect(() => {
       if(state.length) { // if state array have length then its value are newData
           //rest of the code
       }
   }, [state]);
}

Since you wish to add or remove items from updated state after filter, you can do so before actually updating the state, you don't need a useEffect to actually wait for the state to update before performing an action

const MyApp = () => {
   const [state, setState] = React.useState([]);
   const arr1 = [
      {id: 1, name: 'Daryl'},
      {id: 2, name: 'Negan'},
   ];

   const clickHandler = (data) => {
       const newData = arr1.filter(item => item.name === data.name); // some data i wan't to use in useEffect
       // What ever you want to do, you can operate on newData and then finally set updated data to state
       setState(newData);
   };

}

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