reactjs怎么实现监听数据对象

之前一直在用vuejs,因为最近开发要用到reactjs
但是发现他没有vuejs这种可以watch数据对象的方法,
请问下有过reactjs开发经验的人,如果我想监听一个state里的某个属性变化要怎么做?
我现在有个例子因为是定时器的关系,在里面用了setState然后执行后会一直报
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Main component.
我想把他拿出来,但是如果没有监听某个值又不知道怎么放出来

class Main extends React.Component {
        constructor() {
            super();
            this.isCancelTimer = false;
            this.state = {
                isTimeOut: false,
                isSubmit: true
            };
        }
        
        setTimer(severTime) {
            let currentDate = 0,
                timer = null,
                newSeverTime = '',
                counter =()=>{

                    if (currentDate <= 0 || this.isCancelTimer) {
                        clearTimeout(timer);
                        //这里的setState怎么拿到外面
                        this.setState(Object.assign(this.state, {
                            isTimeOut: true,
                            isSubmit: false
                        }))
                    }
                    currentDate--;
                    timer = setTimeout(() => {
                        let day = Math.floor(currentDate / 60 / 60 / 24),
                            hours = Math.floor(currentDate / 60 / 60 % 24),
                            minutes = Math.floor(currentDate / 60 % 60),
                            seconds = currentDate % 60;
                        if (!this.isCancelTimer) {
                            this.setState(Object.assign({}, this.state, {
                                timer: (''+day).padStart(2, 0)+'天'+(''+hours).padStart(2, 0)+'时'+(''+minutes).padStart(2, 0)+'分'+(''+seconds).padStart(2, 0)+'秒'
                            }));
                        }
                        counter();
                    }, 1000);
                };
            // 适配IOS
            newSeverTime = severTime.replace(/-/g, (value) => '/');
            currentDate = +((+new Date(newSeverTime) - (+new Date())) / 1000).toFixed(0);
            currentDate = currentDate.toFixed(0);
            counter();
        }
        componentDidMount() {
            this.setTimer('2017-11-18 17:10:50')
        }
    }
阅读 37.5k
4 个回答

React不监听数据对象,而是通过手动调用setState()方法来触发virtueDiff,以此对比前后来个状态的不同,然后针对性的更改变化了的DOM结构实现数据更新。这是我的理解,欢迎大神拍砖。

如果单纯 React 的话 如果状态发生变化,会触发组件生命周期中的如下方法:

componentWillUpdate(object nextProps, object nextState) 
componentDidUpdate(object prevProps, object prevState) 

如果使用 Redux 等的话,一般状态变化是由 Dispatch 引起的,你在 Dispatch 的回调中执行你想要的就可以了。

可以看看这张图学习一下 React 的生命周期。

记得在componentWillUnmount里面取消定时器,不然就是这个异常

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题