简体   繁体   中英

React.JS Cannot read property 'props' of null Error

just started using react.js.

i keep having the same error. don't know why ?
the error is: 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.

JS Code:

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 ,

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

or change name from do_update to 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.do_update = this.update.bind(this);

line.

If you change your render method to the following, it should work:

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

Change this line this.state = {increasing:false} to this.state = {increasing: false}

That space after the colon matters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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