ComponentWillMount不设置状态React JS

Bok*_*oky 2 reactjs

为什么这不起作用:

class Slider extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            top : 0,
            responsiveImg : ""
        };
    }

    componentWillMount(){
        const bodyWidth = window.innerWidth;
        const responsiveSliderImg = "responsiveSliderImg";

        if((bodyWidth >= 415) && (bodyWidth < 473)){
            this.setState({responsiveImg: responsiveSliderImg});
            console.log("The state is : " + this.state.responsiveImg);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将类名添加到componentWillMount函数中的状态,但它不起作用.在控制台日志中我得到的状态是:,因此状态为空.

任何的想法?

ctr*_*usb 6

状态不会同步更新.来自文档

setState()不会立即改变this.state,但会创建挂起状态转换.调用此方法后访问this.state可能会返回现有值.

尝试检查render方法中的状态.

了解哪些生命周期方法可以在不重新渲染的情况下调用setState也很好.在某些情况下可能会有所帮助.我使用reactcheatsheet作为快速参考.单击"生命周期"过滤器以查看非常有用的表引用.


感兴趣的是.我开发了一个实用程序库来帮助处理与您类似的响应式用例.它为您的组件提供了容器的大小,允许您执行响应式渲染逻辑.它对你有帮助吗?检查它在这里.