[英]How to conditionally render a component that uses hooks, i get error that component that uses hooks cannot do conditionallly render
[英]How to conditionally render a React component that uses 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>
}
有以下錯誤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?
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規則是太嚴格了,但也許有更好的方法。
有條件地呈現使用鈎子的組件的最佳方法是什么?
另一種選擇是拆分組件。
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;
這種方法的優點是您的組件保持小而合乎邏輯。
在您的情況下,您可能在 useState 初始值設定項中擁有超過 '0' 的值,您不希望在條件之前的頂部出現不必要的值。
您不能有條件地使用鈎子,因此將鈎子移到條件上方。
function Apple(props){
const {seeds} = props;
const [bitesTaken, setBitesTaken] = useState(0);
if(!seeds){
return null;
}
return <div>{bitesTaken}</div>
}
您還可以像這樣簡化渲染:
function Apple(props) {
const { seeds } = props
const [bitesTaken, setBitesTaken] = useState(0)
return !!seeds && <div>{bitesTaken}</div>
}
如果seeds
被falsey,那么false
將返回(呈現為無),否則div
將被退回。
我在seeds
添加了雙感嘆號以將其轉換為布爾值,因為如果seeds
undefined
則渲染不會返回任何內容並且 React 會拋出錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.