【发布时间】:2021-02-26 09:23:50
【问题描述】:
我有一个子组件,它通过事件向父组件发出动作:
子组件:
export default function ChildComponent(props) {
const classes = useStyles();
const [value, setValue] = React.useState([0, 5]);
const handleChange = (_, newValue) => {
setValue(newValue);
props.updateData(newValue)
};
return (
<div className={classes.root}>
<GrandSonComponent
value={value}
onChange={handleChange}
/>
</div>
);
}
父组件:
export const ParentComponent = () => {
const [loading, setLoading] = React.useState(true);
const { appData, appDispatch } = React.useContext(Context);
function fetchElements(val) {
fetchData(val);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => { return fetchData() }, []);
async function fetchData(params) {
const res = await axios.get('/url', { params });
appDispatch({ type: "LOAD_ELEMENTS", elements: res.data });
}
return (
<div>
<ChildComponent updateData={fetchElements} />
<div>
.
.
.
)
};
我想知道如何删除这一行// eslint-disable-next-line react-hooks/exhaustive-deps
我需要添加这一行,否则我会看到 eslint 错误:
React Hook useEffect has a missing dependency: 'fetchData'. Either include it or remove the
dependency array.eslintreact-hooks/exhaustive-deps
我需要在第一次渲染页面时使用fetchData(params) 函数,并且当用户更改/单击子组件的值时没有 eslit 警告!
谢谢!
【问题讨论】:
-
这不能回答您的具体问题,但
useEffect(() => { return fetchData() }, []);不是您在第一次渲染时调用该函数的方式。当你从一个使用效果返回时,它会假定它是一个清理函数,在这种情况下运行在 unmount 上。fetchData也返回一个promise,所以当它试图调用它时它会中断。删除return关键字。 -
同样的结果,不能解决问题!
-
这不能回答您的具体问题 - 它不应该回答。它指出了您代码中的第二个问题。
-
您也可以使用
useRef。 stackoverflow.com/a/70255826/8494462
标签: javascript reactjs use-effect