我想通过使用自定义钩子来更新结果中的组件当前状态,但是当我更新它时,显示无限循环渲染。通过使用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>);
};
答案 0 :(得分:1)
不要在功能组件中直接设置状态。使用onCompleted事件:
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>
);
};
答案 1 :(得分:0)
每次加载组件时,您都在呼叫setState({data})
。尝试将setState
放在useEffect
内。
useEffect(() => {
setState({ data })
}, [data])
答案 2 :(得分:0)
尝试在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第二个参数为空数组,则当组件首次呈现并仅设置一次状态时,组件将调用查询。