是否可以在类组件的主体中有一个'useLocation'?反应



我正试图通过React Router Link组件传递一个prop,但当在我的类组件中声明React路由器附带的useLocation钩子时

const location = useLocation()
const { from } = location.state

我收到此错误React Hook "useLocation" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function是否可以在我的类Component中使用useLocation,或者我必须转换为功能组件?

这是我的应用程序结构:

我的功能组件使用React Router Link组件将道具传递给我的类组件:

import { Button } from '@mui/material';
import React from 'react'
import { Link, useLocation } from 'react-router-dom';
import icon from './images/icon.png';
import Main from './Main';
import Screen from './Screen';
const Success = ({ nextStep, handleChange, values, props }) => {
// ...

const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;

// ...
return(

<div>
<p>You have successfully bought: </p>
<p>{`${values.payAmount}`}  BTC on {date}</p>
<Link to='/App' state={{ from: values.payAmount }}>
<Button color="primary"
variant="contained"
style={{ padding:'9px 60px'}}
>Done</Button>
</Link>
</div>
)
}
export default Success;

我的类组件使用useLocation钩子来接收数据:(这是我得到错误的地方(

import React, { Component } from 'react'
import { Link, useLocation } from 'react-router-dom';
class Main extends React.Component {
render() {
const location = useLocation()
const { from } = location.state

return (
<div >
<h1> My Accounts </h1>
<p> You know have {from} in your wallet. </p>
</div>
)
}
}
export default withStyles(styles, { withTheme: true })(Main);

钩子不能在类组件中使用,React Router v6对类组件没有替代方案。你需要以某种方式绕过它。例如,您可以创建另一个功能组件作为包装。类似于:

const LocationComponent = props => {
const location = useLocation()
return <Main location={location} {...props} /> // your component
}

react router文档实际上涵盖了您的情况:https://reactrouter.com/en/6.6.1/start/faq

只需复制示例包装并将其放入js文件中,然后导入即可。

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;
}

相关内容

最新更新