React useEffect无效的挂钩调用.钩子只能在函数组件的主体内部调用



我在使用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)}
}

您不能通过道具传递钩子,更重要的是,您必须在顶层使用钩子,而不是在像handleDelete这样的函数中使用钩子,而是导入钩子并使用它:

// export
export const useFetchAndHighlight = (index) => {...}
// usage
import { useFetchAndHighlight } from './useFetchAndHighlight.js';
// Don't use inside function
useFetchAndHighlight(index);

最新更新