子窗口值未在Window上更新,但我可以看到它在控制台中更新

时间:2016-09-05 09:58:31

标签: reactjs react-redux

我不知道我在这段代码中做错了什么,道具价值'数字'没有在前端更新,虽然在控制台日志中它的值确实增加了。

  import React from 'react';
    import { render } from 'react-dom';


    class Parent extends React.Component{
        constructor(props){
            super(props);
            this.number=0;
            this.changeValue=this.changeValue.bind(this);
        }

        changeValue(){
            console.log('-------------this.number',this.number);
            this.number=this.number+1;
        }

        render(){
            return(
                <div>
                    <Child callMe={this.changeValue} increaseNo={this.number}></Child>
                </div>
            )
        }
    }


    class Child extends React.Component{

        render(){
            return(
                <div>
                    <button onClick={this.props.callMe}>CLick Me</button>
                    <h1>{this.props.increaseNo}</h1>
                </div>
            )
        }
    }

    render(<Parent/> , document.getElementById('root'));

1 个答案:

答案 0 :(得分:1)

您必须将this.number存储在组件state中,只有在state更改或收到新props时才会重新呈现该组件。

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
           number: 0
        }
        this.changeValue=this.changeValue.bind(this);
    }

    changeValue(){
        this.setState({number: this.state.number + 1});
    }

    render(){
        return(
            <div>
                <Child callMe={this.changeValue} increaseNo={this.state.number}></Child>
            </div>
        )
    }
}


class Child extends React.Component{

    render(){
        return(
            <div>
                <button onClick={this.props.callMe}>CLick Me</button>
                <h1>{this.props.increaseNo}</h1>
            </div>
        )
    }
}

jsfiddle