React typescript useParams() 在 useEffect 中总是返回 undefined

时间:2020-12-19 16:28:22

标签: reactjs typescript react-router react-typescript

我正在尝试实现我的配置文件组件在路径 /me 上获取已登录用户的数据并在路径 user/:username 上获取其他人的数据。

以下来自反应路由器博客的例子,我想出了这样的东西:

function App(): JSX.Element {

//...
            <PrivateRoute
                exact
                path="/me"
                render={(props) => (
                    <ProfileComponent {...props} principal={states.username} isMyProfile={true} />
                )}
            />
            <PrivateRoute
                path="/user/:username"
                render={(props) => (
                    <ProfileComponent {...props} principal={states.username} isMyProfile={false} />
                )}
            />
// ...
}


interface ParamTypes {
    path: string;
}

export default function ProfileComponent
  (props: { principal: string; isMyProfile: boolean }): JSX.Element {

  const { path } = useParams<ParamTypes>();

  useEffect(() => {
        async function fetch(username: string) {
            // ...
        }

        props.isMyProfile ? fetch(props.principal) : fetch(path);

    }, [props.principal, path, props.isMyProfile]); 

   // ...
}

但路径始终未定义。我错过了什么?

1 个答案:

答案 0 :(得分:1)

也许这可以帮助您:

import gensim.downloader
glove_vectors = gensim.downloader.load('glove-twitter-25')

如果是您的个人资料,则应未定义 userName 否则您将获得一些价值