繁体   English   中英

反应 useEffect 无效的钩子调用。 钩子只能在 function 组件的主体内部调用

[英]React useEffect Invalid hook call. Hooks can only be called inside of the body of a function component

使用 useEffect 时我总是遇到这个问题,但我看到其他人做得很好。 这是我的代码。 组件 1(父级):

 const UsePrevious = (value)=> {
    const ref = useRef(0);
    useEffect(() => {
      console.log(value)
      ref.current = value;
    });
    return ref.current;
  }

  const FetchAndHighlight = (index) => {
    const prevAmount = UsePrevious(index);
    useEffect(() => {
        if(prevAmount !== index) {
          getNote(props.data.company_id)
          .then(data=>{ 
           return setNotes(data)
          })
          .catch(err=>console.error(err))
        }
    }, [index])

组件 2(儿童)

function handleDelete (row){
  console.log(filteredItems)
  const index = filteredItems.findIndex(r=>r._id===row);
  props.FetchAndHighlight(index);
  deleteNote(row)
  console.log(row)
toast.info('Note deleted sucessfully.')
if(props.combined === 0){props.setCombined(1)} else{props.setCombined(0)}
}

你不能通过 props 传递钩子,更重要的是, 你必须在顶层使用钩子,而不是在handleDelete之类的函数中,而是导入钩子并使用它:

// export
export const useFetchAndHighlight = (index) => {...}

// usage
import { useFetchAndHighlight } from './useFetchAndHighlight.js';

// Don't use inside function
useFetchAndHighlight(index);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM