使用useSelector的无限循环useEffect

时间:2020-06-26 10:37:11

标签: reactjs react-redux react-hooks

// 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 ]);

我的问题是,每当我在deuseEffect内调用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
}, [ ]);

1 个答案:

答案 0 :(得分:1)

好吧,我弄清楚了,我在Reducer中的一种类型将descriptions保留为空数组,因此它可以无限地重新渲染。