我有一个非常标准的设置,一个带有页面的路由器:
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/5
这样的页面时,一切都工作正常。 User
组件在正确实例化时遇到一些问题。所有其他页面都正常工作,我还有另一个使用 url 参数 (project/:id
) 的页面,它也工作正常。
import React from "react";
...
export default class User extends React.Component {
constructor() {
super();
console.log(this);
...
}
render() {
return ...
}
这是我在控制台中得到的内容。
我确信这又是最愚蠢的事情,但我无法辨别出来......
最佳答案
我认为您缺少以下内容,请尝试替换您的构造函数:
constructor(props) {
super(props);
console.log(this.props)
}
尝试一下,您应该从 this.props
获得输出。
The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. Source: ReactJS.org Component Docs.
关于reactjs - React this.props 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858542/