Reactjs can';t将函数作为prop传递,则';这总是一个警告?
这是我的代码:Reactjs can';t将函数作为prop传递,则';这总是一个警告?,reactjs,react-hooks,Reactjs,React Hooks,这是我的代码: const handleNotification = React.useCallback( type => { setSuccess(type); setTimeout(() => reset(), 1500); }, [reset] ); const sendRequest = React.useCallback( async () => { // don't send again w
const handleNotification = React.useCallback(
type => {
setSuccess(type);
setTimeout(() => reset(), 1500);
},
[reset]
);
const sendRequest = React.useCallback(
async () => {
// don't send again while we are sending
if (isSending) return;
// update state
setIsSending(true);
// send the actual request
try {
await axios({
method: "post",
url: NONCOM_SEND_MAIL_URL,
headers: {},
data: {
clientId,
userId,
email,
subject: "Non-Compliant Certificate",
templateCode: "REQNOTMET",
entityId: entity_id
}
});
handleNotification(true);
} catch (e) {
setError(e);
handleNotification(false);
}
// once the request is sent, update state again
if (isMounted.current)
// only update if we are still mounted
setIsSending(false);
},
[isSending, clientId, userId, email, entity_id, handleNotification]
); // update the callback if the state changes
我收到这样的警告:
“reset”函数使useCallback Hook(第35行)的依赖项在每次渲染时发生更改。将其移动到useCallback中。或者,将“reset”定义包装到它自己的useCallback()钩子中
正如你所看到的,我已经把它包在里面了?在这种情况下我做错了什么?重置是此组件中的功能属性。为什么这不起作用?请发布重置函数好吗?React不喜欢传递给钩子的异步函数。相反,尝试将异步函数包装在传递给
useCallback
hook的函数中,然后将其作为IIFE调用或写入。类似这样的内容:const sendRequest=React.useCallback(()=>(async()=>{…};)()
因为reset()
是通过父级的道具来实现的,就像任何道具一样,它可以(潜在地)更改每个渲染,所以最好的做法是将它放在依赖项列表中。有关父项中更改的示例,请参见此问题。将其移动到useCallback回调中意味着将定义移动到内部,即不再作为道具传递,而是在使用它的位置定义它(如果您可能的话)。将“重置”定义包装到其自己的useCallback()中钩子再次意味着在这个组件中移动定义,并且不再通过道具传递它。您正在对handleNotification()
的useCallback中使用它,但此消息意味着在另一个useCallback中定义它(即const reset=useCallback(…
)