我有一个非常标准的设置,一个带页面的路由器
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"));
Run Code Online (Sandbox Code Playgroud)
除非我去一个页面像一切都可以正常使用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 ...
}
Run Code Online (Sandbox Code Playgroud)
这是我在控制台中得到的
我确定这是最糟糕的事情,但我无法挑出来......
Bru*_*uce 50
我想你错过了以下内容,替换你的构造函数
constructor(props) {
super(props);
console.log(this.props)
}
Run Code Online (Sandbox Code Playgroud)
尝试一下,你应该从this.props得到输出
在安装React组件之前,会调用它的构造函数.在为React.Component子类实现构造函数时,应该在任何其他语句之前调用super(props).否则,this.props将在构造函数中未定义,这可能导致错误.
就我而言,我忘记绑定我正在调用的方法,这就是props未定义的原因。
constructor(props) {
super(props);
this.changeScreenToForm = this.changeScreenToForm.bind(this);
}
changeScreenToForm() {
this.props.app.changeScreen(Form);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39953 次 |
| 最近记录: |