javascript 类组件的主体中是否可以有一个'useLocation'?React [duplicate]

fjaof16o  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(191)
    • 此问题在此处已有答案**:

How to pass params into link using React router v6?(5个答案)
4个月前关闭。
我试图通过React Router Link组件传递一个prop,但是当在我的类组件中声明React Router附带的useLocation hook时:

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路由器链路组件向我的类组件传递一个prop:

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);
yqyhoc1h

yqyhoc1h1#

钩子不能用在类组件中,React Router v6也没有类组件的替代品。你需要以某种方式绕过去。例如,你可以创建另一个功能组件作为 Package 。类似于:

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

shyt4zoc2#

React路由器文档实际上涵盖了您的情况:https://reactrouter.com/en/6.6.1/start/faq
只需复制示例 Package 器并将其放入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;
}

相关问题