0

我正在尝试使用链接将数据传递到新页面,这样做我使用了以下代码。

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

输出是一个空对象。

{}

两个页面都是类组件

4

1 回答 1

1

我假设您正在使用react-router.

在您使用的第一页中,<Link>...</Link>您正在做正确的事情。

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

如果你使用一个函数

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

import { useLocation } from 'react-router';

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

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

在里面location.state你有你从上一页传递的状态。

如果你使用一个类

在这种情况下,事情会稍微复杂一些,但您可以使用withRouterin order 在组件中注入locationprops。

所以,首先你需要导入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您就拥有了从上一页传递的状态。

于 2021-11-23T18:09:45.803 回答