类型错误:从 react-router 使用 useParams 时,无法读取未定义的属性“匹配" [英] TypeError: Cannot read property 'match' of undefined when using useParams from react-router

查看:35
本文介绍了类型错误:从 react-router 使用 useParams 时,无法读取未定义的属性“匹配"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么会出现上述错误.我在 props.match.params.languagename 中使用了 props 方式,它工作得很好.

我没有在下面的代码中包含所有导入.

<预><代码>从反应路由器"导入 { useParams };const App = () =>{const topicState = useSelector(state => state.topics);const dispatch = useDispatch();const { 语言名称 } = useParams();useEffect(() => {调度(获取GitHubTrendingTopics());}, [派遣]);const handleRepositoryPages = () =>{const repositoryPages = topicState.find(主题状态 =>topicState.name === 语言名);如果(存储库页面)return <RepositoryPage repositoryPages={repositoryPages}/>;};返回 (<><路由器><标题主题={topicsState}/><开关><Route path="/" 精确><仪表板主题={topicsState}/></路线><路线路径=/语言/:语言名称"精确的渲染={handleRepositoryPages()}/><重定向到="/"/></开关></路由器></>);};

解决方案

您只能在作为 Router 组件的子组件的组件中使用 useParams,但是 App 是您的情况的父级.

Router 组件将包含 match 的上下文注入到它下面的树中,useParams 钩子会在内部使用useContext 钩子.

I can't understand why it gives me the above error. I used the props way with props.match.params.languagename and it works just fine.

I did not include all imports in the code below.


import { useParams } from 'react-router';

const App = () => {
  const topicsState = useSelector(state => state.topics);

  const dispatch = useDispatch();
  const { languagename } = useParams();

  useEffect(() => {
    dispatch(fetchGitHubTrendingTopics());
  }, [dispatch]);

  const handleRepositoryPages = () => {
    const repositoryPages = topicsState.find(
      topicState => topicState.name === languagename
    );
    if (repositoryPages)
      return <RepositoryPage repositoryPages={repositoryPages} />;
  };
  return (
    <>
      <Router>
        <Header topics={topicsState} />
        <Switch>
          <Route path="/" exact>
            <Dashboard topics={topicsState} />
          </Route>
          <Route
            path="/language/:languagename"
            exact
            render={handleRepositoryPages()}
          />

          <Redirect to="/" />
        </Switch>
      </Router>
    </>
  );
};

解决方案

You can only use useParams in a component that is a child of your Router component, but App is the parent in your case.

The Router component injects the context containing the match into the tree below it which will be read by the useParams hook by internally using the useContext hook.

这篇关于类型错误:从 react-router 使用 useParams 时,无法读取未定义的属性“匹配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆