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.
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? I tried adding recurrsive function with setTimeout
after let seconds
declaration but it doesn't propagate down to the component on change.
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
export default compose(
withState('seconds', 'updateSeconds', 0),
lifecycle({
componentDidMount() {
const { seconds, updateSeconds} = this.props;
setTimeout(
() => {
updateSeconds(seconds + 1);
},
1000,
);
}
}),
pure,
)(Timer);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.