首页 > 解决方案 > 从 RN 中的 setTimeout 或 Alert 回调中调度 redux 操作时性能下降

问题描述

对此可能有一个很好的解释,但目前我很困惑。

所以用例是我想在一个setTimeout块中或Alert.alert在 RN 的回调中调度一个 redux 操作。我注意到的是,如果代码以这种方式运行,那么它会慢得多。

例如,代码如下:

import React from 'react';
import { connect } from 'react-redux';
import { addTag } from '../redux/actions';
import { Button, View, Alert } from 'react-native';

export const HomePerfTest = connect(
  null,
  dispatch => ({
    addTag: (tag, category) => dispatch(addTag(tag, category)),
  })
)(props => (
  <View>
    <Button
      title="Press me"
      onPress={() => {
        addRandomTags(props.addTag);
      }}
    />
    <Button
      title="Press me"
      onPress={() => {
        Alert.alert('Add random tags', null, [
          {
            text: 'Yes',
            onPress: () => {
              addRandomTags(props.addTag);
            },
          },
          {
            text: 'No',
          },
        ]);
      }}
    />
  </View>
));

const addRandomTags = addTag => {
  for (let i = 0; i < 10; i++) {
    measure(
      () =>
        addTag(
          {
            name: 'test' + i,
          },
          'test'
        ),
      'addTag'
    );
  }
};

const measure = (f, label) => {
  var t0 = new Date().getTime();
  const value = f();
  var t1 = new Date().getTime();
  console.log(label + ' took ' + (t1 - t0) + ' milliseconds.');
  return value;
};

现在,当按下第一个按钮时,addTag运行时间为 0-1 毫秒。当按下第二个按钮(然后单击是)时,需要 4-8 毫秒,因此会慢几倍。

这种情况并没有那么糟糕,但我已经在我的应用程序的另一个页面中实现了类似的东西,其中差异很大。正常运行大约需要 2 毫秒,如果从Alert回调中运行,则需要 >100 毫秒才能执行。

现在,我通过使用与 RN Alert 不同的警报模块来解决问题。但是我注意到如果我只是将代码包装在setTimeout

setTimeout(() => addRandomTags(props.addTag));

任何解释将不胜感激。

更新- 我在包装代码时也可以看到完全相同的延迟requestAnimationFrame

标签: javascriptreact-nativeredux

解决方案


推荐阅读