[英]How to use the useDispatch() hook inside the useEffect() hook?
[英]How to use function parameter inside useEffect hook
我有点击事件监听器,我正在接收数据参数。 在这个 function 内部,我正在设置 state。 现在我正在尝试根据当前的 state 更改 state ,我需要useEffect
来实现这一点。 但我不知道如何在其中使用 function 数据参数。 这是代码:
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]);
}
您不需要直接使用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]);
}
由于您希望在过滤后从更新的 state 中添加或删除项目,因此您可以在实际更新 state 之前执行此操作,您不需要 useEffect 来实际等待 Z9ED39E2EA931586B6A985A6942EF7 更新之前执行操作
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);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.