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