如何在重构中使用 setTimeout 更新状态?
How to update state using setTimeout in recompose?
我想学习重构,所以我从一个简单的组件开始:
const timer: React.SFC<MyProps | any> = ({ seconds }) => (
<span>{ seconds }</span>
);
我想以某种方式使用重组将 seconds
传递给它,它会每秒递增。
let seconds = 0;
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
如何正确地增加 seconds
props 以便在 props 更改时传播到组件?我尝试在 let seconds
声明后使用 setTimeout
添加递归函数,但它不会在更改时传播到组件。
我最终得到了这个
let seconds = 0;
incrementSeconds();
function incrementSeconds() {
seconds += 1;
setTimeout(
() => {
incrementSeconds();
},
1000,
);
}
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
而不是withProps
,我会使用withState
然后像
一样更新状态
export default compose(
withState('seconds', 'updateSeconds', 0),
lifecycle({
componentDidMount() {
const { seconds, updateSeconds} = this.props;
setTimeout(
() => {
updateSeconds(seconds + 1);
},
1000,
);
}
}),
pure,
)(Timer);
我想学习重构,所以我从一个简单的组件开始:
const timer: React.SFC<MyProps | any> = ({ seconds }) => (
<span>{ seconds }</span>
);
我想以某种方式使用重组将 seconds
传递给它,它会每秒递增。
let seconds = 0;
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
如何正确地增加 seconds
props 以便在 props 更改时传播到组件?我尝试在 let seconds
声明后使用 setTimeout
添加递归函数,但它不会在更改时传播到组件。
我最终得到了这个
let seconds = 0;
incrementSeconds();
function incrementSeconds() {
seconds += 1;
setTimeout(
() => {
incrementSeconds();
},
1000,
);
}
export default compose(
withProps(() => ({ seconds })),
pure,
)(Timer);
而不是withProps
,我会使用withState
然后像
export default compose(
withState('seconds', 'updateSeconds', 0),
lifecycle({
componentDidMount() {
const { seconds, updateSeconds} = this.props;
setTimeout(
() => {
updateSeconds(seconds + 1);
},
1000,
);
}
}),
pure,
)(Timer);