Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

reactjs - React this.props is undefined

I've got a pretty standard setup, a router with pages:

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"));

Everything is working perfectly except when I go to a page like site.tld/#/user/5. The User component has some trouble getting instantiated properly. All other pages are working, I also have another page that uses url parameters (project/:id) and it is working fine as well.

import React from "react";
...

export default class User extends React.Component {

  constructor() {
    super();

    console.log(this);
    
    ...
  }

  render() {
    return ...
  }

This is what I get in the console.

enter image description here

I'm sure it's the dumbest thing ever again, but I can't pick it out...

question from:https://stackoverflow.com/questions/42858542/react-this-props-is-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you're missing the following, try replacing your constructor:

constructor(props) {
    super(props);

    console.log(this.props)
}

Try it out, you should get output from 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...