gpt4 book ai didi

reactjs - 无限循环 useEffect 和 useSelector

转载 作者:行者123 更新时间:2023-12-04 04:05:21 25 4
gpt4 key购买 nike

// get state
const { inscriptions } = useSelector( state => state.user );

// flag
const instances = Object.keys(inscriptions).length;

// dispatch
const dispatch = useDispatch();

const getInscriptions = () => dispatch( getInscriptionsAction() );

useEffect( () => {
// call api only if empty
if(instances === 0) {
const queryToAPI = async () => {
getInscriptions();
}

queryToAPI();
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ instances, inscriptions ]);
我的问题是,每当我调用强制存储更新的 de useEffect 内部的 API 时,这会使组件重新渲染,从而启动无限循环。我也不能输入类似 if(isntances === 0) return null; 的内容大约在 useEffect 下方,因为我的铭文数组可以为空,我尝试添加所有类型的标志,但它保持无限循环。有任何想法吗?
==================编辑================================ =
好的,现在我已经实现了一些建议,但问题仍然存在,无限循环仍然存在。
// get state
const { inscriptions } = useSelector( state => state.user );

// flag
const instances = Object.keys(inscriptions).length;

// dispatch
const dispatch = useDispatch();

// const getInscriptions = () => dispatch( getInscriptionsAction() );

const getInscriptions = useCallback(
() => dispatch( getInscriptionsAction() ),
[ dispatch, getInscriptionsAction ]
);

useEffect( () => {
// call api only if empty
if(instances === 0) {
// const queryToAPI = async () => {
getInscriptions();
// }

// queryToAPI();
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ ]);

最佳答案

好吧,我想通了,我在 Reducer 中的一个类型保留了对空数组的描述,因此它正在无限地重新渲染。

关于reactjs - 无限循环 useEffect 和 useSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62592956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com