无法读取 React-Hooks 中未定义的属性“pathname”
2020-12-15
193
之前用起来还好。
但是现在不行了。
这是什么原因?
该怎么办?
无法读取location prop。
在header代码中添加了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 Router代码
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>
);
1个回答
不确定它是如何工作的,但您需要将路由器位置作为 prop 传入,或者在导出 Header 组件时使用
withRouter
,例如在 Header 组件文件中有
import { withRouter } from "react-router";
然后在导出时:
export default withRouter(Header);
Jayce444
2020-12-15