[英]where to set `setInterval` when working with recompose?
我正在嘗試構建一個簡單的計時器,它將在點擊時啟動和停止。 我的所有項目都是基於功能組件(使用重構),所以我不確定在哪里設置setInterval
。
這是我嘗試玩的東西,直到我完全丟失了存放setInterval
地方,所以我將能夠在onStop
fn上清除它(這將觸發按鈕) - 因為在功能組件中沒有this
我可以把計時器和刪除它...什么是功能組件的方式呢?
https://codepen.io/anon/pen/jQQZrm?editors=0010
有什么建議么 ? - 使用react-native感謝。
這里需要3個不同的狀態處理程序: stopTimer
, startTimer
和updateValue
(我使用的代碼與你的代碼稍有不同)。
在startTimer
您需要創建由計時器運行updateValue
的計時器。 換句話說,您需要間接調用另一個狀態處理程序。
沒有辦法做到這一點 。 但。 您可以將這些處理程序拆分為兩組:“value + updateValue”和“stopTimer + startTimer + intervalId”。 然后,您將能夠從第一組中獲取狀態處理程序作為props
:
const EnchanceApp = compose(
withStateHandlers({
timer: 0,
}, {
updateValue: ({timer}) =>
() => ({timer: timer + 1})
}),
withStateHandlers({
timerId: 0,
}, {
startTimer: ({timerId}, {updateValue}) =>
() => {
clearInterval(timerId);
return {
timerId: setInterval(updateValue, 1000)
};
},
stopTimer: ({timerId}) =>
() => clearInterval(timerId)
})
)(App);
工作完美,我的代碼示例:
const BgList = ({ bgs }) => (
<PoseGroup>
{bgs.map(item => <StyledBg key={item} style={{backgroundImage: 'url(/img/'+item+'.jpg)'}} />)}
</PoseGroup>
);
const enhance = compose(
withStateHanlders(
() => ({
index: 0,
isVisible: false,
bgs: _.shuffle([0,1,2,3]),
timerId: 0,
}),
{
startTimer: () => ({timerId}, {updateValue}) => {
clearInterval(timerId);
return {
timerId: setInterval(updateValue, 5000)
};
},
stopTimer: ({timerId}) => () => clearInterval(timerId),
updateValue: ({bgs}) =>
() => {
return ({bgs: _.shuffle(bgs)})
},
},
),
lifecycle({
componentDidMount() {
const {timerId, updateValue} = this.props;
this.props.startTimer({timerId}, {updateValue})
}
}),
)
const BlockAnimated = enhance(({
bgs
}) => {
return (
<BgList bgs={bgs} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.