【问题标题】:where to set `setInterval` when working with recompose?使用重组时在哪里设置`setInterval`?
【发布时间】:2019-05-01 15:30:15
【问题描述】:

我正在尝试构建一个简单的计时器,该计时器将在点击时启动和停止。 我所有的项目都是基于功能组件的(使用重组),所以我不确定在哪里设置setInterval

这是我试图玩的东西,直到我完全迷失了在哪里存储 setInterval 所以我可以在 onStop fn 上清除它(这将在一个按钮上触发) - 就像功能一样组件没有this,我可以放置计时器并将其从中删除......功能组件的做法是什么?

https://codepen.io/anon/pen/jQQZrm?editors=0010

有什么建议吗? - 使用本机反应 谢谢。

【问题讨论】:

    标签: javascript react-native recompose


    【解决方案1】:

    您需要 3 个不同的状态处理程序:stopTimerstartTimerupdateValue(我使用的命名与您的代码略有不同)。

    startTimer 中,您需要创建计时器,该计时器通过计时器运行updateValue。换句话说,您需要从另一个状态处理程序间接调用一个状态处理程序。

    no way doing that。但。您可以将这些处理程序分成两组:“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);
    

    【讨论】:

      【解决方案2】:

      完美运行,我的代码示例:

      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} />
      

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 2011-03-22
        • 2010-10-02
        • 1970-01-01
        • 2019-04-02
        • 2020-03-07
        • 2016-12-25
        • 1970-01-01
        • 2019-01-05
        相关资源
        最近更新 更多