【问题标题】:Cannot read property 'pathname' of undefined in React-Hooks无法读取 React-Hooks 中未定义的属性“路径名”
【发布时间】:2021-03-25 17:43:49
【问题描述】:

以前效果很好。

但是现在不行了。

什么原因?

我该怎么办?

无法读取位置属性。

在标头代码中添加了 withRouter,

那么这次FriendsHeader出错了。

这是我的 FriendsHeader 代码

import React from "react";
import styled from "styled-components";
import { Container } from "../BaseLabel";
import { Link, withRouter } from "react-router-dom";

const FriendstHeader = ({ location: { pathname } }) => {
  return (
    <>
      <FriendContainer>
            <Icons>
              {
                <Links to="/setting">
                  <div current={pathname === "/setting"}>
                    <img src={Cog} width="18px" height="18px" alt="" />
                  </div>
                </Links>
              }
            </Icons>
      </FriendContainer>
    </>
  );
};
export default withRouter(FriendstHeader);

这个 React 路由器代码

import React from "react";
import {
  HashRouter as Router,
  Route,
  Switch,
  Redirect,
} from "react-router-dom";

export default () => (
  <Router>
    <>
      <Header />
      <Switch>
        <Route path="/" exact component={Friends} />
        <Route path="/chats" component={Chats} />
        <Route path="/shap" component={Shap} />
        <Route path="/more" component={More} />
        <Route path="/setting" component={Setting} />
        <Route path="/covid19" component={Covid19} />
        <Route path="/kakaotv" component={KakaoTV} />
        <Route path="/fun" component={Fun} />
        <Route path="/entertain" component={Entertain} />
        <Route path="/sports" component={Sports} />
        <Route path="/openchats" component={OpenChat} />
        <Redirect from="*" to="/" />
      </Switch>
      <Navgation />
    </>
  </Router>
);

【问题讨论】:

标签: reactjs properties react-router react-hooks location


【解决方案1】:

不确定它是如何工作的,但是您需要将路由器位置作为道具传递,或者在导出 Header 组件时使用withRouter,例如在你的 Header 组件文件中有

import { withRouter } from "react-router";

然后在导出时:

export default withRouter(Header);

https://reactrouter.com/web/api/withRouter

【讨论】:

  • 在header代码中添加了withRouter,那么这次FriendsHeader中出现了错误。这段代码有withRouter。
  • @eeezkim 你有错字,你有loaction。应该是location
  • 谢谢你:) 太好了??
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 2021-11-24
  • 2017-12-30
  • 1970-01-01
  • 2021-04-08
  • 2021-12-29
  • 1970-01-01
  • 2021-03-10
相关资源
最近更新 更多