如何在不将状态传递给子组件的情况下更新状态

How to update state without passing it to child component

本文关键字:状态 组件 更新 情况下      更新时间:2023-09-26

这是我当前的React.js代码的一个稍微简化的例子。

https://jsfiddle.net/69z2wepo/14668/

var Main = React.createClass({
    getInitialState: function(){
        return {
            showText: false
        }
    },
    handleClick: function(){
        this.setState({
            showText: true
        })
    },
    render: function() {
        return (
            <div>
                <button onClick={this.handleClick}>Press me</button>
                <Child showText={this.state.showText} />
            </div>
        )
    }
});
var Child = React.createClass({
    render: function(){
        if(this.props.showText){
            return (
                <div>
                    Pressed
                </div>
            )
        }
        return (
            <div>
                Default text
            </div>
        )
    }
});
React.render(<Main/>, document.getElementById('container'));

当我改变我的showText属性为真,并把它传递给我的子组件,我怎么能立即切换我的showText为假?

我想要的是类似这样的东西,除了回调不应该被发送给child。

handleClick: function(){
    this.setState({
        showText: true
    }, function(){
        showText: false
    })
}

我的Main组件应该只发送true的子按钮时,按下。否则我希望它的状态一直为假

在父组件上调用setState将导致render函数触发,这反过来也将重新呈现Child组件。你应该只需要在你的父节点上设置setState,其余的层次结构应该根据父节点的状态重新呈现。

var updating = false;
var Main = React.createClass({
    getInitialState: function(){
        return {
            showText: false
        }
    },
    handleClick: function(){
        updating = !updating;
        alert('is updating: ' + updating);
        if(updating) {
            this.setState({
                showText: true
            });
        }
    },
    render: function() {
        return (
            <div>
                <button onClick={this.handleClick}>Press me</button>
                <Child showText={this.state.showText} />
            </div>
        )
    }
});

或另一种方式:

var Child = React.createClass({
    shouldComponentUpdate: function(nextProps, nextState) {
        return nextProps.showText;
    },
    render: function(){
        if(this.props.showText){
            return (
                <div>
                    Pressed
                </div>
            )
        }
        return (
            <div>
                Default text
            </div>
        )
    }
});
https://jsfiddle.net/69z2wepo/14670/

从你的描述中我可以收集到,那么这可能是你想要的:https://jsfiddle.net/4vL3mubf/2/

子组件在第一次点击后永远不会改变,但我认为这是你想要的。

Main组件基本上可以通过以下函数来切换状态:

componentDidUpdate: function(prevProps, prevState) {
    if (this.state.showText === true) {
        this.setState({showText: false});
    }
},

更新了Jim对shouldComponentUpdate的使用。https://jsfiddle.net/4vL3mubf/3/