如何有条件地渲染使用钩子的 React 组件

Jor*_*dan 4 reactjs react-hooks

以下(尽管是人为的)组件违反了react-hooks/rules-of-hooks(通过eslint)

function Apple(props){
  const {seeds} = props;
  if(!seeds){
    return null;
  }
  const [bitesTaken, setBitesTaken] = useState(0);
  return <div>{bitesTaken}</div>
}

Run Code Online (Sandbox Code Playgroud)

出现以下错误 React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

我理解钩子需要以相同的顺序调用,但是这种条件渲染(只要返回之前没有调用钩子)并不会阻止以相同的顺序调用钩子。我认为eslint规则是太严格了,但也许有更好的方法。

有条件地渲染使用钩子的组件的最佳方法是什么?

Ber*_*rtC 5

另一种选择是拆分组件。

import React,{useState} from 'react';

const Apple = (props) => {
    const {seeds} = props;
    return !!seeds && <AppleWithSeeds />;
};

const AppleWithSeeds =(props) => {
    const [bitesTaken] = useState(0);
    return <div>{bitesTaken}</div>
};

export default Apple;
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您的组件保持较小且符合逻辑。

在您的情况下, useState 初始值设定项中可能有超过“0”的内容,您不希望在条件之前的顶部出现不必要的内容。