反应 this.props 未定义 [英] React this.props is undefined

查看:49
本文介绍了反应 this.props 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常标准的设置,一个带页面的路由器:

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

一切正常,除非我转到像 site.tld/#/user/5 这样的页面.User 组件在正确实例化时遇到了一些麻烦.所有其他页面都在工作,我还有另一个页面使用 url 参数 (project/:id),它也工作正常.

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.

我敢肯定这是有史以来最愚蠢的事情,但我挑不出...

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

推荐答案

我认为您缺少以下内容,请尝试更换您的构造函数:

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

constructor(props) {
    super(props);

    console.log(this.props)
}

试试看,你应该会从 this.props 得到输出.

Try it out, you should get output from this.props.

React 组件的构造函数在挂载之前被调用.在为 React.Component 子类实现构造函数时,你应该在任何其他语句之前调用 super(props) .除此以外,this.props 将在构造函数中未定义,这可能导致错误.来源:ReactJS.org 组件文档.

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.

这篇关于反应 this.props 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆