【问题标题】:Redirect to passing some value to the redirected-to component重定向到将一些值传递给重定向到的组件
【发布时间】:2023-03-17 17:25:02
【问题描述】:

一旦用户单击按钮,我想将一些值从一个组件传递到另一个组件。

第一个组件 (Survey) 的值为 survey --> 用户单击按钮 --> 第二个组件 (Details) 呈现 survey

为了实现,我使用来自react-router-domRedirect

function Survey({survey}) {
....
// There is a button that triggers the below if clause. The redirect works but it seems the state is not sent.
    if (surveyPage === true) {
        return <Redirect to={{
            pathname: '/detail',
            state: { location: survey }
        }}

    }

    return("something")

}

第二个组件

function Details(){
    console.log( this.props.location.state.location) // Cannot read property 'props' of undefined
    return "test"
}

无法读取未定义的属性“道具”

我也试过了:

function Details({survey){
    console.log(survey) // Undefined
    return "test"
}

function Details({ location: survey }){
    console.log(survey) // Undefined
    return "test"
}

我真的不明白我做错了什么。我正在关注文档: https://reacttraining.com/react-router/web/guides/primary-components

【问题讨论】:

  • 这不是关于react-route-dom,而是关于如何将 props 属性传递给功能组件。由于错误是props undefined
  • 我也试过没有this,但还是有类似的错误

标签: javascript reactjs


【解决方案1】:

thisfunctional 组件中不可访问。你需要这样做:

import { useHistory } from "react-router-dom";

function Details(props){
    const history = useHistory();
    console.log(history.location.state.location);

    return <p>Test</p>
}

export default Details;

希望这对你有用。

【讨论】:

    【解决方案2】:

    要将您的组件连接到路由信息,您应该使用 withRouter HOC 或 useHistory 钩子。

    withRouter 示例:

    import { withRouter } from "react-router";
    
    function Details(props){
        console.log(props.history.location.state.location);
    
        return <p>Test</p>
    }
    
    export default withRouter(Details);
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多