【发布时间】:2019-07-23 02:36:51
【问题描述】:
React 文档明确指出calling hooks conditionally will not work。 From the original React hooks presentation,原因是因为 React 使用你调用 hooks 的顺序来注入正确的值。
我明白这一点,但现在我的问题是是否可以从带有钩子的函数组件中提前返回。
那么这样的事情是否允许?:
import React from 'react';
import { useRouteMatch, Redirect } from 'react-router';
import { useSelector } from 'react-redux';
export default function Component() {
const { match } = useRouteMatch({ path: '/:some/:thing' });
if (!match) return <Redirect to="/" />;
const { some, thing } = match.params;
const state = useSelector(stateSelector(some, thing));
return <Blah {...state} />;
}
从技术上讲,useSelector 钩子是有条件地调用的,但是它们被调用的顺序在渲染之间不会改变(即使可能会调用更少的钩子)。
如果不允许这样做,您能否解释一下为什么不允许这样做并提供一般的替代方法来提前返回带有钩子的函数组件?
【问题讨论】:
-
您在自己的问题中有答案 - 这是不允许的,因为
React uses the order you call hooks to inject the correct value。它实际上可能适用于您的情况,您将收到的警告只是警告而不是错误。但是,当您实际上忘记了该组件的下落并决定添加更多钩子或重新安排条件时,您可能会在以后陷入错误。
标签: javascript reactjs react-hooks