【问题标题】:React couldn't pass a data from one class component into another using LinkReact 无法使用 Link 将数据从一个类组件传递到另一个类组件
【发布时间】:2022-01-02 03:46:55
【问题描述】:

我正在尝试使用 Link 将数据传递到新页面,为此我使用了以下代码。

 <Link
            className="option"
            to={{
              pathname: this.state.pathname,
              state: id
            }}
          >
            <span className="color-primary"> <button style={{ color: "white" }} 
              className="transaction-button"><i className="material-icons" style={{ fontSize: "18px" }}>sync_alt</i> Transaction</button>
            </span>
          </Link>

在路由的页面中,我尝试通过以下代码处理数据。

console.log(this.props)

输出是一个空对象。

{}

两个页面都是类组件

【问题讨论】:

    标签: reactjs react-class-based-component react-link


    【解决方案1】:

    我假设您使用的是react-router

    在您使用&lt;Link&gt;...&lt;/Link&gt; 的第一页中,您做的是正确的事情。

    此时有两种选择:可以使用函数或类来创建组件。

    如果你使用函数

    在第二页,要取你传递的数据,你必须导入useLocation

    import { useLocation } from 'react-router';
    

    然后,在函数内部,你必须调用它并从中提取状态:

    const location = useLocation();
    console.log(location.state);
    

    location.state 中,您拥有从上一页传递的状态。

    如果你使用一个类

    在这种情况下,事情会稍微复杂一些,但您可以使用 withRouterlocation 注入到您的组件 props 中。

    所以,首先你需要导入PropsTypeswithRouter

    import PropTypes from 'prop-types';
    import { withRouter } from 'react-router';
    

    那么你必须这样写你的类:

    class Child extends React.Component {
        static propTypes = {
            location: PropTypes.object.isRequired,
        };
    
        render() {
            const { location } = this.props;
    
            console.log(location.state);
    
            return {
               <div> ... </div>
            };
        }
    }
    export withRouter(Child);
    

    这样在location.state 中你就有了你从上一页传递过来的状态。

    【讨论】:

    • 我尝试了您的建议,但是当我正在处理基于类的组件时出现以下错误。不能在类组件中调用 React Hook “useLocation”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用
    • 在我之前的回答中,我假设您使用的是函数而不是类。现在,如果您使用类,答案也会更加完整和准确
    • 非常感谢。
    • 如果答案有用,您可以接受答案,这样有相同问题的其他人可以轻松找到解决方案
    猜你喜欢
    • 2021-10-15
    • 2021-04-16
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2018-05-02
    • 2021-01-02
    相关资源
    最近更新 更多