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)
推荐的方法是什么?
| 归档时间: |
|
| 查看次数: |
985 次 |
| 最近记录: |