Yus*_*suf 6 reactjs react-router-dom
Failed to compile. Attempted import error: 'withRouter' is not exported from 'react-router-dom'.
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的,我还安装了react-router-dom一个反应路由,现在我已经将应用程序重新旋转了 10 次
import React from 'react';
import {withRouter} from 'react-router-dom';
import './menu-item.scss';
const MenuItem = ({ title, imageUrl, size, history }) => (
<div className={`${size} menu-item`}>
<div
className='background-image'
style={{
backgroundImage: `url(${imageUrl})`,
}}
/>
<div className='content'>
<h1 className='title'>{title.toUpperCase()}</h1>
<span className='subtitle'>SHOP NOW</span>
</div>
</div>
);
export default withRouter(MenuItem);
Run Code Online (Sandbox Code Playgroud)
Dre*_*ese 14
如果您不小心安装了react-router-domv6,则withRouterHOC 将不再存在。要么恢复到 v5 ( runnpm install -s react-router-dom@5 ),要么推出您自己的自定义withRouterHOC 以注入您需要的 props,或者将组件转换为函数组件并使用 React hooks。
withRouter高阶组件来自常见问题解答:withRouter 发生了什么我需要它
Run Code Online (Sandbox Code Playgroud)import { useLocation, useNavigate, useParams, } from "react-router-dom"; function withRouter(Component) { function ComponentWithRouterProp(props) { let location = useLocation(); let navigate = useNavigate(); let params = useParams(); return ( <Component {...props} router={{ location, navigate, params }} /> ); } return ComponentWithRouterProp; }
现在也不再有一个history对象可供使用,它被navigate通过useNavigate钩子访问的函数所取代。目前尚不清楚history以前在哪里使用过,但如果您需要强制导航,则以下是访问导航的方式。如果继续使用 v6,则以下是如何访问该navigate功能。
import React from 'react';
import { useNavigate } from 'react-router-dom';
import './menu-item.scss';
const MenuItem = ({ title, imageUrl, size }) => {
const navigate = useNavigate();
// navigate("/targetPath")
return (
<div className={`${size} menu-item`}>
<div
className='background-image'
style={{
backgroundImage: `url(${imageUrl})`,
}}
/>
<div className='content'>
<h1 className='title'>{title.toUpperCase()}</h1>
<span className='subtitle'>SHOP NOW</span>
</div>
</div>
)
};
export default MenuItem;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23270 次 |
| 最近记录: |