Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React this.props is undefined

Tags:

reactjs

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...

like image 883
php_nub_qq Avatar asked Mar 17 '17 13:03

php_nub_qq


People also ask

Why my props is undefined react?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

How do you make props not undefined?

The "cannot set property 'props' of undefined" error occurs when we add an extra set of parenthesis when declaring a class component in React. js. To solve the error, remove the parenthesis after Component in your class declaration, e.g. class App extends Component {} .

How do you define a react component?

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.


1 Answers

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.

like image 165
Bill Avatar answered Sep 20 '22 02:09

Bill