我想使用自定义钩子更新我的组件当前状态,但是当我更新它时,它向我显示无限循环渲染。 通过使用 useState(( 钩子。我是反应钩子的新手。
import React, { useMemo, useState, useReducer, useEffect, useCallback } from 'react';
import getAllFaqs from './faqQuery.graphql';
import { useFaq } from '../../peregrine/talons/Faq/useFaq';
const Faq = props => {
const [state, setState] = useState({})
const talonProps = useFaq({
query: getAllFaqs
});
const { data, error, loading } = talonProps;
setState({data})
console.log("Thank data", state)
return (<div>its Working</div>);
};
尝试在 useEffect 挂钩中运行以下代码:
const talonProps = useFaq({
query: getAllFaqs
});
const { data, error, loading } = talonProps;
setState({data})
那看起来像:
import React, { useMemo, useState, useReducer, useEffect, useCallback } from 'react';
import getAllFaqs from './faqQuery.graphql';
import { useFaq } from '../../peregrine/talons/Faq/useFaq';
const Faq = props => {
const [state, setState] = useState({})
useEffect(() => {
const talonProps = useFaq({
query: getAllFaqs
});
const { data, error, loading } = talonProps;
setState({data})
console.log("Thank data", state)
}, [])
return (<div>its Working</div>);
};
每次组件呈现时,它都会调用您的查询并设置状态,从而导致组件再次重新渲染,该组件调用您的查询并设置状态,导致组件再次重新呈现......在第二个参数为空数组的情况下使用 useEffect 将使组件在组件首次呈现时调用查询并仅设置一次状态。
不要直接在功能组件中设置状态。使用完成事件:
import React, { useMemo, useState, useReducer, useEffect, useCallback } from 'react';
import getAllFaqs from './faqQuery.graphql';
import { useFaq } from '../../peregrine/talons/Faq/useFaq';
const Faq = props => {
const [state, setState] = useState({})
const talonProps = useFaq({
query: getAllFaqs,
onCompleted: ({ data, error, loading }) => setState({data})
});
console.log("Thank data", state)
return (
<div>its Working</div>
);
};
每次加载组件时都会调用setState({data})
。尝试将setState
放入useEffect
。
useEffect(() => {
setState({ data })
}, [data])