道具更改时,ReactJS子组件未更新

时间:2018-12-14 08:26:04

标签: reactjs

我是ReactJS的新手,正在做一些练习,这是我的代码。当我单击“显示进度”按钮时,我期望ProgresssetInterval触发并显示最近的时间,但这种方式不起作用。它只是显示值  第一次通过并保持不变。

class App extends React.Component{
    constructor(props){
        super(props);
        this.showProgress = this.showProgress.bind(this);

        this.state = {
            now: new Date(),
            content: null
        };
        this.timerId = null;
    }

    showProgress(){
        let content = <Progress now={ this.state.now } />;
        this.setState({ content: content });
    }

    componentDidMount(){
        this.timerId = setInterval(()=>this.setState({now: new Date()}), 500);
    }

    componentWillUnmount(){
        clearInterval(this.timerId);
    }

    render(){
        return (
            <div>
                <button onClick={ this.showProgress }>Show Progress</button>
                { this.state.content }
            </div>
        )
    }
}

function Progress(props){
    return (
        <h2>{ props.now.toString() }</h2>
    );
}

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

如果将<Progress now={this.state.now}>嵌入App的{​​{1}}逻辑中,那么时间将由render刷新。

我想知道这是怎么回事?

1 个答案:

答案 0 :(得分:1)

您正在以状态存储组件。我什至不知道100%是否可行。

您不能执行以下操作吗?

class App extends React.Component{
    constructor(props){
        super(props);
        this.showProgress = this.showProgress.bind(this);

        this.state = {
            now: new Date(),
            content: null,
            showProgress: false,
        };
        this.timerId = null;
    }

    showProgress(){
        this.setState({ showProgress: true });
    }

    componentDidMount(){
        this.timerId = setInterval(()=>this.setState({now: new Date()}), 500);
    }

    componentWillUnmount(){
        clearInterval(this.timerId);
    }

    render(){
        return (
            <div>
                <button onClick={ this.showProgress }>Show Progress</button>
                {this.state.showProgress && <Progress now={ this.state.now } />}
            </div>
        )
    }
}

function Progress(props){
    return (
        <h2>{ props.now.toString() }</h2>
    );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
相关问题