【问题标题】:this.props.params not existing after passing parameter on react-router在 react-router 上传递参数后 this.props.params 不存在
【发布时间】:2017-03-29 10:23:42
【问题描述】:

我将参数从 react-router 的路由路径传递给组件,但在 this.props 对象中,'params' 不存在

const routes = (
    <Router forceRefresh={true}>
        <div>
            <Route exact path="/" component={Firstpage}/>
            <Route exact path="/projects" component={Projectslist}/>
            <Route exact path="/projects/:projectId" component={Singleproject}/>
        </div>
    </Router>
);

这是我的组件:

class Singleproject extends React.Component{
    constructor(props) {
        super(props);
    }

    componentWillMount(){
        window.document.title = "Wploper | Project title";
    }
    render(){
        return(
            <div>
                <Mainheader/>
                <div id="single-project-container" className="sheet-max-width">
                    <h2>{this.props.params}</h2>
                </div>
                <Mainfooter/>
            </div>
        );
    }
}

并且对象(this.props)没有参数: enter image description here

【问题讨论】:

  • 你使用的是哪个 react-router 版本?
  • 同时粘贴您调用接收参数的路由的代码。
  • 第四版。
  • 我在构造函数中使用console.log对其进行测试

标签: reactjs react-router


【解决方案1】:

针对 react-router v4 测试 在您的 Singleproject 组件中,您可以通过以下方式获取参数:

this.props.match.params.projectId

下面是一个代码示例:

    class ForgotPassword extends Component {
        constructor (props,context){
            super(props,context);
            this.state={
                busy : true,
                sessionId : localStorage.getItem('sessionId') || null,
                resetKey : this.props.match.params.resetKey || ''
            };
            console.log(this);
        }
}

【讨论】:

  • 为我工作!谢谢你。奇怪我找了这么久。
【解决方案2】:

在 react-router 版本 4 中,您可以使用 this.props.match.params 获取路径参数

【讨论】:

    【解决方案3】:

    可以通过context从路由中获取参数。 this.context.params.projectId

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-22
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2021-04-16
      • 2016-05-25
      相关资源
      最近更新 更多