簡體   English   中英

為什么 react-router-dom useParams 鈎子在上下文中不起作用?

[英]Why doesn't react-router-dom useParams hook work within Context?

我在一組個人資料頁面之間共享了一個上下文。 上下文負責從數據庫加載和設置用戶的配置文件,如下所示:

const Profile = props => {
    const { userProfile } = useContext(ProfileContext);
    return userProfile && (
        <div className="profile-container">
            ...stuff
        </div>
    );
};

export default Profile;

...路線:

<BrowserRouter>
    <Header />
    <main className="main-container">
        <Switch>
            ...other routes
            <ProfileContextProvider>
                <Route path="/profile/:id" exact component={Profile} />
                <Route path="/settings" exact component={Settings} />
            </ProfileContextProvider>
        </Switch>                       
    </main>
    <Footer />
</BrowserRouter>

上下文本身非常簡單:

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

export const ProfileContext = React.createContext({
    userProfile: {},
    setUserProfile: () => {}
});

ProfileContext.displayName = "ProfileContext";

const ProfileContextProvider = props => {
    const { id } = useParams(); //always undefined!
    const [userProfile, setUserProfile] = useState(null);

    useEffect(() => {
        loadData();
    }, []);
    
    const loadData = async () => {
        ...api call to load data
    };
    
    return (
        <ProfileContext.Provider value={{ 
            userProfile,
            setUserProfile
        }}>
            {props.children}
        </ProfileContext.Provider>
    );
};

export default ProfileContextProvider;

但是,在那里使用 useParams() 是行不通的。 “id”始終未定義。 如果我將此 useParams() 用法移動到 Profile 組件本身,它就可以正常工作。 這對我沒有好處,因為在加載所有配置文件之前,在上下文中加載數據時,我需要對路線做出決定。 我需要它在上下文中工作!

這可能嗎? 難道我做錯了什么?

上下文本身就是不同的管理和查詢參數應該從頁面道具到上下文集變量然后它可以工作

您的 ProfileContextProvider 位於定義“id”參數的路由之外……這行不通。

暫無
暫無

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

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