我有一个用来调用自定义钩子的组件。
自定义钩子如下:
import { useQuery } from 'react-apollo';
export function useSubscription() {
const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)
if (loading) return false
if (error) return null
return data
}
然后我正在使用的导致错误的组件是:
export default function Form(props) {
const router = useRouter();
let theSub = useSubscription();
if (theSub === false) {
return (
<Spinner />
)
} // else I'll have the data after this point so can use it.
useEffect(() => {
if (!isDeleted && Object.keys(router.query).length !== 0 && router.query.constructor === Object) {
setNewForm(false);
const fetchData = async () => {
// Axios to fetch data
};
fetchData();
}
}, [router.query]);
// Form Base States
const [newForm, setNewForm] = useState(true);
const [activeToast, setActiveToast] = useState(false);
// Form Change Methods
const handleUrlChange = useCallback((value) => setUrl(value), []);
const handleSubmit = useCallback(async (_event) => {
// Submit Form Code
}, [url, selectedDuration, included, excluded]);
return (
<Frame>
My FORM
</Frame>
)
}
有什么想法吗?
答案 0 :(得分:0)
您可以在第一次渲染组件时使用useEffect来调用钩子。
export default function Form(props) {
const router = useRouter();
const [theSub, setTheSub] = useState(null);
useEffect(() => { setTheSub(useSubscription()); }, []);
if (theSub === false) {
return (
<Spinner />
)
} // else I'll have the data after this point so can use it.
// I have some other states being set and used related to the form e.g:
// const [whole, setWhole] = useState(true);
return (... The form ...)