簡體   English   中英

React - Hooks 的順序變化在哪里?

[英]React - Where is the change in order of Hooks?

import React, { Fragment } from 'react'
import styled from 'styled-components'

export const routes = [
    { path: '/', name: 'Home', children: <HomePage />, exact: true, strict: true },
    ...
]

const Wrapper = styled.div``

const Breadcrumbs = () =>
{
    const getRoutes = () => routes.filter(({ path }) => useRouteMatch({ path }))
    const getRouteMatches = () => getRoutes().map(({ path, name }) => ({ ...useRouteMatch({ path }), name }))

    return (
        <Wrapper>
            { getRouteMatches().map(({ url, name }) => <Fragment key={ url }>
                <Link to={ url }>{ name }</Link>
                <span>/</span>
            </Fragment>) }
        </Wrapper>
    )
}

這段代碼違反了 Hook 的 React 規則,因為 Hook 的順序是可變的。 請幫助我理解為什么會發生該錯誤。

首先,我只使用一種類型的 Hook。 那么,如果是一個 Hook,那么為什么 Hook(s) 的順序很重要呢?

此外,React 規則是否關心每次渲染的 Hook數量

useRouteMatch與箭頭函數調用一起使用,鈎子只能在組件內直接使用;

文檔

不要在循環、條件或嵌套函數中調用 Hook。 相反,始終在 React 函數的頂層使用 Hook。 通過遵循此規則,您可以確保每次渲染組件時以相同的順序調用 Hook。 這就是允許 React 在多個 [hooks] 之間正確保留 Hooks 狀態的原因。

如果您從 React 函數的頂層以外的函數調用鈎子,則順序可能會有所不同。 鈎子的順序對於 React 知道哪個狀態屬於渲染之間的哪個鈎子是必要的。

只在頂層調用鈎子。 https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

它有助於 React 在多個 useState 和 useEffect 調用之間正確保留 Hooks 的狀態。

您需要在頂層移動此鈎子的使用,而不是函數調用。

    const getRoutes = () => routes.filter(({ path }) => useRouteMatch({ path }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM