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

use*_*977 5 javascript setstate reactjs react-props

我最近看到了这种类型的反应模式,其中状态是通过使用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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

推荐的方法是什么?

小智 4

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

\n\n

来自反应文档:

\n\n
\n

render() 函数应该是纯函数,这意味着它不会修改组件状态,每次调用它都会返回相同的结果,并且它不会直接与浏览器交互。如果您需要与浏览器交互,请在 componentDidMount() 或其他生命周期方法中执行您的工作。保持 render() 纯粹可以让组件更容易被思考。

\n
\n\n

也看看这里这里

\n