阵营this.props未定义

问题描述:

我有一个非常标准的设置,配页阵营this.props未定义

import React from "react"; 
import ReactDOM from "react-dom"; 
import { IndexRoute, Router, Route, Link, hashHistory as history } from "react-router"; 

import Layout from "./pages/Layout"; 
... 
import User from "./pages/User"; 

ReactDOM.render(
    <Router history={history}> 
     <Route path="/" component={Layout}> 
     <IndexRoute component={...}/> 
     <Route path="project/create" component={...}/> 
     <Route path="project/:id" component={...}/> 
     <Route path="user/:id" component={User}/> 
     <Route path="*" component={...}/> 
     </Route> 
    </Router>, 
    document.getElementById("app-root")); 

一切工作完全不同的,当我去一个网页一样site.tld/#/user/5User成分有一定的麻烦实例化一个路由器正常。所有其他网页正在工作,我也有另一个页面使用网址参数(project/:id),它也工作得很好。

import React from "react"; 
... 

export default class User extends React.Component { 

    constructor() { 
    super(); 

    console.log(this); 

    ... 
    } 

    render() { 
    return ... 
    } 

这是我在控制台中看到

enter image description here

我敢肯定它是最愚蠢的事情以后再,但我不能把它挑出来......

+0

通常,您将构造函数中收到的道具传递给组件超类:https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors- when-declaring-components-using-es6-classes/2781 –

+0

尝试在'render()'方法中记录'this.props'来验证。 –

+0

@HunterMcMillen你是对的,道具在渲染中可用,但不在构造函数中,在构造函数中传递道具使得我的代码没有区别:/ –

我认为你错过了以下内容,替换你的构造函数

constructor(props) { 
    super(props); 

    console.log(this.props) 
} 

试一试,你应该从这里得到输出。props

React组件的构造函数在挂载之前被调用。 在实现React.Component子类的构造函数时, 应在任何其他语句之前调用super(props)。否则, this.props将在构造函数中未定义,这可能会导致 错误。

+1

我试过了,它不起作用。我在所有页面中都有相同的构造函数,并且可以在其他页面的构造函数中使用道具。 –

+0

@php_nub_qq你做超(道具)吗?不只是super()而不是空的构造函数()而不是构造函数(道具) – Bruce

+0

是的,我在我发布之前尝试过。事实证明,在这个组件中,道具在render()中可用,但在构造函数中不可用。我想知道为什么.. –