如何在useEffect挂钩中使用函数参数

时间:2020-05-27 14:16:45

标签: reactjs react-hooks

我有click事件侦听器,并且正在其中接收数据参数。在此功能的内部,我正在设置状态。现在,我试图根据当前状态更改状态,我需要useEffect来实现。但是我不知道如何在其中使用函数数据参数。这是代码:

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]);
}

2 个答案:

答案 0 :(得分:0)

您不需要直接使用newData,因为您将其值设置为state

只需通过以下方式更改您的组件:

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]);
}

答案 1 :(得分:0)

由于您希望在过滤器之后添加或删除更新后的状态中的项目,因此可以在实际更新状态之前执行此操作,因此不需要useEffect来实际等待状态更新后再执行操作

{
   "place": "London",
   "temp": 15,
   "weather": "Cloudy"
}