我正在使用React来呈现我的web应用程序所需的一些组件,并且我有一个带有播放和停止按钮的计时器。我从获取请求中检索所有时间记录,并且每次更改我的组件时都要重新渲染组件,我该怎么做?原始ReactJS更新属性
我的一切工作,但有一个简单的setInterval来调用this.forceUpdate(功能),但给我的警告:
警告:forceUpdate(...):只能更新一安装或安装部件。这通常意味着您在卸载的组件上调用了forceUpdate()。这是一个没有操作。请检查TimerBox组件的代码。
我的组件:
var TimerBox = React.createClass({
displayName: 'TimerBox',
updateTime: function() {
getTime();
this.forceUpdate();
this.props.records = allRecords(); // get all time records
},
componentDidMount: function() {
setInterval(this.updateTime, 1000); // set interval to each second
},
render: function() {
this.props.records = allRecords();
return (
React.createElement('div', { className: 'main-timer-box' },
React.createElement('div', { className: 'timer-box' }, hours + ' hours, ' + minutes + ' minutes and ' + seconds + ' seconds',
React.createElement(ControlButton, null)),
React.createElement('hr', null)
)
);
}
});
我是新来reactjs和我开始使用无JSX,巴贝尔或反应的WebPack,我不wan't改变整个代码,现在。
我只是想知道我可以声明一个属性,然后在每次改变值时使属性调用重新渲染。
谢谢。
工作更新我的组件,谢谢。但是我现在对setState有同样的警告“......只能更新挂载或挂载组件,这通常意味着你在卸载的组件上调用了setState()......”似乎问题在于调用updateTime函数 –
这是因为'setState'在超时时被调用,当它实际上被调用时,你的组件已被卸载。为避免这种情况,你必须在'componentWillUnmount'生命周期方法中清除超时,以确保'setState'仅在组件未被卸载时才被调用 –
请参阅更新的答案或使用@finalfreq解决方案:) –