【问题标题】:access object from Link state in a class component从类组件中的链接状态访问对象
【发布时间】:2021-06-11 13:27:33
【问题描述】:

我有一个 Link 路由器,可以像这样将我从一个页面带到另一个页面:

  <Link
  to={{
    pathname: `/details/${submission.id}`,
    state: { mySubmission: submission }
  }}>

此链接将我带到另一个称为详细信息的页面。我想传入一个我从链接开始到我的详细信息页面的页面创建的对象

我正在尝试获取存储在 mySubmission 中的信息,但我成功了,非常感谢任何帮助

下面是我的详细信息页面

class Details extends React.Component {
   componentDidMount() {
    const { match: { params } } = this.props;
  
    axios.get(`/details/${params.userId}`)
      .then(({ data: user }) => {
        console.log('user', user);
  
        this.setState({ user });
      });
  }
  //let currentSubmission;
  //var currentSubmission = props.location.state.mySubmission;
  //let var = this.props.location.state;

    render() {
        return (

    <React.Fragment> 
      <Carousel>
        <Carousel.Item>
          <img src={logo}  alt="logo"/>
        </Carousel.Item>
        <Carousel.Item>
          <img src={logo}  alt="logo"/>  
        </Carousel.Item>
        <Carousel.Item>
          <img src={logo}  alt="logo"/>
        </Carousel.Item>
      </Carousel>

        {/*Right now everything is hard coded but should be passed in as props in future */}
      <div className="card-body">
        <h1 className="title-event">{}</h1>
        <br></br>
        <h2 className="title-location">Kiev, Ukraine</h2>
        <br></br>
        <h1>{this.props.location.state}</h1> {/*not working */}

最后,我想在详细信息页面中显示对象的字段。

提前谢谢你!!!

PS:这是Link API,我在其中获取状态属性,表示我可以将对象传递给 Link

【问题讨论】:

    标签: reactjs react-router react-link


    【解决方案1】:

    我认为你需要用withRouter 包装你的组件才能正确接收状态。

    然后你从props.location.state得到信息

    查看this sandbox

    【讨论】:

    • 你能详细说明一下吗? withRouter 是从哪里来的?顺便说一句,我们有两个文件要链接
    • 它来自 react 路由器 dom 库。检查这个https://reactrouter.com/web/api/withRouter
    • @fabiocontreras 您找到解决问题的方法了吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2020-11-20
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多