簡體   English   中英

如何從函數或事件內部的反應掛鈎設置數據?

[英]How to set data from a react hook inside of a function or event?

我試圖學習創建鈎子,以便可以重復使用必須在不同組件中更改的數據。

我使用的是Material UI的標簽 ,需要使用useTab,這是一個自定義鈎子,用於更改標簽ID。

import React, { useContext } from 'react';
import { ProductsContext } from './ProductsContext';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { useTab } from '../../hooks/tab';

const ProductsNav = () => {
    const {products, categories, loading} = useContext(ProductsContext);
    const [tabValue] = useTab(0);

    const handleTabChange = (e, newTabValue) => {
        useTab(newTabValue);
    }

    return (
        <div className="products">
            <AppBar position="static">
                <Tabs value={tabValue} onChange={ handleTabChange }>
                    {
                        Array.from(categories).map(category => (
                            !category.unlisted && (<Tab label={category.title} key={category.id}/>)
                        ))
                    }
                </Tabs>
            </AppBar>

        </div>
    ); 
};

export default ProductsNav;

我知道它是通過文檔中的子功能來完成此操作的,但是我試圖不僅以自己的方式復制和粘貼並執行此操作。

這是我自定義的useTab鈎子:

import {useState, useEffect} from 'react';

export const useTab = (selectedTab) => {
    const [tabValue, setTabValue] = useState(0);
    useEffect(() => {
        setTabValue(selectedTab);
    }, []);
    return [tabValue];
}

我當然會出錯,無法在函數內部使用鈎子,但是我很困惑其他方法。

如何從useTabs更改tabValue?

錯誤可能在這里:

const handleTabChange = (e, newTabValue) => {
    useTab(newTabValue);
}

您違反了掛鈎的主要規則之一

不要在循環,條件或嵌套函數中調用Hook。 相反,請始終在您的React函數的頂層使用掛鈎。

這個規則的原因有點復雜,但是基本上可以歸結為應在React功能組件的頂層調用鈎子的想法,因為必須確保每次運行組件函數時都可以運行鈎子。

因此,為什么會出現錯誤“我不能在函數內部使用鈎子” ...

無論如何,目前還不清楚為什么要在此處使用帶有useEffect()的自定義鈎子。 這似乎完全沒有必要-導航組件內部的常規useEffect()鈎子已經足夠了:

const ProductsNav = () => {
    const {products, categories, loading} = useContext(ProductsContext);
    const [tabValue, setTabValue] = useState(0);

    const handleTabChange = (e, newTabValue) => {
        setTabValue(newTabValue);
    }

    return (
        <div className="products">
            <AppBar position="static">
                <Tabs value={tabValue} onChange={ handleTabChange }>
                    {
                        Array.from(categories).map(category => (
                            !category.unlisted && (<Tab label={category.title} key={category.id}/>)
                        ))
                    }
                </Tabs>
            </AppBar>

        </div>
    ); 
};

暫無
暫無

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

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