javascript – 使用this.state在渲染中设置状态

我最近看到过这种类型的反应模式,其中使用this.state在渲染中设置状态:

class ShowMe extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            showButton: false,
        };
    }

    render() {
        if (this.props.show) {
            this.state.showButton = true; //setting state in render!!
        }

        return (
            <div>
                <div> Show or hide button </div>
                {this.state.showButton && <Button content='Btn'/>}
            </div>
        )
    }
}

这似乎是一种反模式.这会导致错误吗?它似乎工作正常.

我只想使用组件生命周期来设置状态:

class ShowMe extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            showButton: false,
        };
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.show) {
            this.setState({
                showButton: true,         
            })
        }
     }

    render() {
        return (
            <div>
                <div> Show or hide button </div>
                {this.state.showButton && <Button content='Btn'/>}
            </div>
        )
    }
}

推荐的方式是什么?

解决方法:

渲染应该始终是纯净的,没有任何副作用,所以这肯定是一个不好的做法.

来自React文档:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

看看herehere.

上一篇:React学习笔记2


下一篇:React组件的3种状态和setState循环调用