Javascript 获取 TypeError:this.props 在 ReactJs 上未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32732989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:08:31  来源:igfitidea点击:

Getting TypeError: this.props is undefined on ReactJs

javascriptreactjs

提问by hilarl

I am trying to do the tutorial: https://facebook.github.io/react/docs/tutorial.html

我正在尝试做教程:https: //facebook.github.io/react/docs/tutorial.html

import React, { PropTypes } from 'react';
import classnames from 'classnames';
import styles from './CommentBox.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import $ from 'jquery';

@withStyles(styles)
class CommentBox extends React.Component {

    constructor() {
        super();
        this.state = {data: []};
    }

    loadCommentsFromServer() {
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            cache: false,
            success: function(data) {
                this.setState({data: data});
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        })
    }

    componentDidMount() {
        this.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
    }

    render() {

        let url="/public/comments.json"

        return (
            <div className="commentBox">
                <h1>Comments</h1>
                <CommentList data={this.state.data} />
                <CommentForm />
            </div>
        );
    }

}

class CommentList extends React.Component {

    render() {

        let data = this.props.data

        var commentNodes = data.map(function (comment) {
          return (
            <Comment author={comment.author}>
              {comment.text}
            </Comment>
          );
        });

        return (
          <div className="commentList">
            {commentNodes}
          </div>
        );
    }
};

class Comment extends React.Component {
    render() {
        return(
            <div className="comment">
            <h2 className="commentAuthor">
              {this.props.author}
            </h2>
            {this.props.children}
          </div>
        );
    }
}

class CommentForm extends React.Component {
  render() {
    return (
      <div className="commentForm">
        Hello, world! I am a CommentForm.
      </div>
    );
  }
};

export default CommentBox;

However, the tutorial is a bit outdated and I am using React 0.14-rc1 with ES6 syntax. I have tried my best to follow the tutorial and implementing it the 0.14 way. Was able to get to this point but now getting the error:

但是,本教程有点过时,我使用的是带有 ES6 语法的 React 0.14-rc1。我已尽力遵循教程并以 0.14 的方式实现它。能够达到这一点,但现在出现错误:

TypeError: this.props is undefined

Could not figure out the issue. Any idea why? Thanks

无法弄清楚问题。知道为什么吗?谢谢

回答by Henrik Andersson

When using Reactand ES6 classesReact won't auto bind functions that is declared on your class.

当使用ReactES6 类时,React 不会自动绑定在您的类上声明的函数。

Therefore either use this.loadCommentsFromServer.bind(this)or use arrow functions

因此使用this.loadCommentsFromServer.bind(this)或使用箭头函数

loadCommentsFromServer = () => {}

loadCommentsFromServer = () => {}

回答by Aditya Singh

With the shift of React from createClass to ES6 classeswe need to handle the correct value of thisto our methods on our own, as mentioned here: http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classesChange your code to have the method bounded to correct value of this in consructor:

随着 React 从 createClass 转移到ES6 classes我们需要自己处理this我们方法的正确值,如下所述:http: //www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes更改您的代码以将方法绑定到构造函数中 this 的正确值:

export default class ComponentClass extends React.Component {
  constructor(props) {
      super(props);
      this._myHandler = this._myHandler.bind(this);
  }

  _myHandler(props) {
    console.log(props);
  }

  render() {
    return (
        <div className="col-xs-6 col-md-4">
            <button type="button" className="btn btn-danger" onClick={this._myHandler}><i className="fa fa-trash"> Delete</i></button>
        </div>
    )
  }
}

The no autobindingwas a deliberate step from React guys for ES6 classes. Autobinding to correct context was provided with React.createClass. Details of this can be found here: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

no autobinding是 React 人员为 ES6 类设计的一个有意的步骤。自动绑定到正确的上下文提供了React.createClass。详情请见:https: //facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

So based on this you could also change your code as:

因此,基于此,您还可以将代码更改为:

export default class ComponentClass extends React.Component {
  _myHandler = (props) => {
    console.log(props);
  }

  render() {
    return (
        <div className="col-xs-6 col-md-4">
            <button type="button" className="btn btn-danger" onClick={this._myHandler}><i className="fa fa-trash"> Delete</i></button>
        </div>
    )
  }
}

回答by Prudhvi Raj Mudunuri

Passing the propsto the constructor will help:

将 传递props给构造函数将有助于:

constructor(props) {
    super(props);
}

回答by Hemadri Dasari

The ajax code can be improved like below using arrow function to avoid scope issues and to access props inside

ajax 代码可以像下面这样使用箭头函数进行改进,以避免范围问题并访问里面的道具

 loadCommentsFromServer = () => {
    $.ajax({
        url: this.props.url,
        dataType: 'json',
        cache: false,
        success: (data) => {
            this.setState({data: data});
        },
        error: (xhr, status, err) => {
            console.error(this.props.url, status, err.toString());
        }
    })
}

回答by Bryan Gromadzki

Although all of the above answers are technically correct, they did not work in my case. I received some crazy error 'Missing class properties transform' so rather than trying to figure that out I defined the handler right in the event like so:

尽管上述所有答案在技术上都是正确的,但在我的情况下它们不起作用。我收到了一些疯狂的错误“缺少类属性转换”,所以我没有试图弄清楚我在事件中定义了处理程序,如下所示:

export class ComponentClass extends React.Component{
  _myHandler(event) {
    event.preventDefault();
    console.log(this.props.thingIPassedIn);
  }
  render() {
    return <Button onClick={(event) => this._myHandler(event)} type="button" className="btn btn-danger">Click Me!</Button>;
  }
}

You can also pass parameters this way.

您也可以通过这种方式传递参数。

export class ComponentClass extends React.Component{
  _myHandler(thingIPassedIn) {
    console.log(thingIPassedIn);
  }
  render() {
    return <MyOtherComponent defNotAnEvent={(thingIPassedIn) => this._myHandler(thingIPassedIn)} />;
  }
}

回答by KRIPA SHANKAR JHA

I am also new to React and one thing is worth to notice while working with state and props inside function is USE FUNCTION VARIABLE ie.

我也是 React 的新手,在使用函数内部的 state 和 props 时值得注意的一件事是 USE FUNCTION VARIABLE 即。

func(){this.setState}result error func=()=>{this.setState}will work

func(){this.setState}结果错误 func=()=>{this.setState}将起作用

same is the case with

同样是这种情况

this.propsinside function

this.props内部功能

Note even you are not using function.bind(this) with its context inside constructor.

请注意,即使您没有在构造函数中使用 function.bind(this) 及其上下文。