[英]How to update state using setTimeout in recompose?
I wanted to learn recompose so I started with a simple component component: 我想学习重组,因此从一个简单的组件开始:
const timer: React.SFC<MyProps | any> = ({ seconds }) => (
<span>{ seconds }</span>
);
I'd like to somehow pass seconds
to it using recompose, where it would increment each second. 我想使用recompose将
seconds
传递给它,它会每秒递增。
let seconds = 0;
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
How can I properly increment seconds
props so it is propagated to the component on props change? 如何正确增加
seconds
道具,以便在道具更改时传播到组件? I tried adding recurrsive function with setTimeout
after let seconds
declaration but it doesn't propagate down to the component on change. 在
let seconds
声明之后,我尝试使用setTimeout
添加递归函数,但它不会在更改后传播到组件。
I ended up with this 我结束了这个
let seconds = 0;
incrementSeconds();
function incrementSeconds() {
seconds += 1;
setTimeout(
() => {
incrementSeconds();
},
1000,
);
}
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
Instead of withProps
, I would make use of withState
and then update the state like 代替
withProps
,我将使用withState
,然后像
export default compose(
withState('seconds', 'updateSeconds', 0),
lifecycle({
componentDidMount() {
const { seconds, updateSeconds} = this.props;
setTimeout(
() => {
updateSeconds(seconds + 1);
},
1000,
);
}
}),
pure,
)(Timer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.