反应this.setState不会重新呈现组件

时间:2018-02-17 14:59:49

标签: javascript reactjs

我有一个发送帖子请求的按钮,通过this.setState方法更新this.state中的serviceStatus。但是当我按下按钮时它不会触发重新渲染。根据反应文件,它应该触发重新投降。代码如下。如何重新渲染组件?

class PowerStatus extends Component {
    constructor(props) {
        super(props);
        this.title = this.props.title
        this.state = {
            initial: {
                loaded: false,
            }
        }
        this.onClick = this.onClick.bind(this);
    }

    async componentDidMount() {
        ... 
    }

    async onClick() {
        const url = `/api/widgets/start`;
        const body = {
            title: this.title
        }
        try {
            const { data } = await axios.post(url, body);
            this.setState(() => {
                return {
                    ...this.state,
                    serviceStatus: data.start,
                }
            });
        } catch (e) {
            alert("Could not turn on service.")
        }
    }

    render() {
        if (this.state.initial.loaded) {
            const colour = this.state.serviceStatus ? "green" : "red";
            return (
                <Grid.Column
                    width={3}
                    style={{textAlign: 'center'}}
                    onClick={this.onClick}
                    className="img-icon"
                    verticalAlign='middle'>
                    <i 
                        className={`fas fa-power-off fa-5x ${colour}`}></i>
                </Grid.Column>
            );
        } else {
            return (
                <div/>
            )
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在构造函数中初始化状态。

$Params = @{
    ResourceGroupName = $ResourceGroupName
    ResourceType      = 'Microsoft.Web/sites/functions'
    ResourceName      = $AppName
    ApiVersion        = '2015-08-01'
}
Get-AzureRmResource @Params

然后你可以更新它并返回你的函数,如:

constructor(props) {
  ...
  this.onClick = this.onClick.bind(this);
  this.state = { 
     loaded: false,
     serviceStatus: null
  };
}