简体   繁体   English

React.JS无法读取null错误的属性“ props”

[英]React.JS Cannot read property 'props' of null Error

just started using react.js. 刚开始使用react.js。

i keep having the same error. 我一直有同样的错误。 don't know why ? 不知道为什么吗?
the error is: Uncaught TypeError: Cannot read property 'props' of null 错误是: Uncaught TypeError: Cannot read property 'props' of null
i know that the error happens when i click the button. 我知道单击按钮会发生错误。 specifically i think it's in the update() method. 具体来说,我认为它在update()方法中。

JS Code: JS代码:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
    constructor(){
        super();
        this.state = {increasing:false}
        this.do_update = this.update.bind(this);
    }
    update(){
        ReactDOM.render(
            <App val={this.props.val+1} />,
            document.getElementById('app')
        );
    }
    componentWillReceiveProps(nextProps){
        this.setState({increasing: (nextProps.val > this.props.val) })
    }
    render(){
        return <button onClick={this.update}>{this.props.val}</button>
    }
}

App.defaultProps = {val:0}
ReactDOM.render(<App />,document.getElementById('app'))

In this case you need pass to onClick do_update instead of update , 在这种情况下,您需要传递给onClick do_update而不是update

return <button onClick={ this.do_update }>{ this.props.val }</button>

or change name from do_update to update 或将名称从do_update更改为update

this.update = this.update.bind(this);

The update handler, when invoked, will not get the correct context for the 'this' keyword... which is why presumably your code has the: 调用更新处理程序时,将不会为'this'关键字获取正确的上下文...这就是为什么您的代码具有以下内容的原因:

this.do_update = this.update.bind(this);

line. 线。

If you change your render method to the following, it should work: 如果将render方法更改为以下方法,则该方法应该起作用:

render(){
        return <button onClick={this.do_update}>{this.props.val}</button>
    }

Change this line this.state = {increasing:false} to this.state = {increasing: false} 将此行this.state = {increasing:false}更改为this.state = {increasing: false}

That space after the colon matters. 冒号后面的空间很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM