react本机性能问题

IT技术 reactjs react-native
2021-05-07 15:10:54

我使用 coincap api 首先获取大约 1500+ 加密货币的数据,然后使用 Web-socket 来更新加密货币的更新值。

我在这里使用 redux 来管理我的状态

在 My 中componentDidMount(),我正在调用一个redux 操作 fetchCoin来获取硬币的value

componentDidMount() {
    this.props.fetchCoin()
  }

然后在return我做这样的事情

 <FlatList
           data={this.state.searchCoin ? displaySearchCrypto : this.props.cryptoLoaded}
           renderItem={({ item }) => (
           <CoinCard
              key={item["short"]}
              coinShortName = {item["short"]}
              coinName = {item["long"]}
              coinPrice = {item["price"].toFixed(2)}
              percentChange = {item["perc"].toFixed(2)}
              />

然后我有一个网络套接字,它像这样更新加密货币的value

 componentDidUpdate() {
    if (this.state.updateCoinData || this.updateCoinData.length < 1 ) {
      this.updateCoinData = [...this.props.cryptoLoaded];
     this.setState({updateCoinData: true})
    }
      this.socket.on('trades', (tradeMsg) => {
      for (let i=0; i< this.updateCoinData.length; i++) {

        if (this.updateCoinData[i]["short"] == tradeMsg.coin ) {

        //Search for changed Crypto Value
       this.updateCoinData[i]["perc"] = tradeMsg["message"]["msg"]["perc"]
       this.updateCoinData[i]["price"] = tradeMsg['message']['msg']['price']

        //Update the crypto Value state in Redux
        this.props.updateCrypto(this.updateCoinData);

          }
        }
      })
  }

现在,虽然这项工作有效,但问题是这会像地狱一样拖慢我的应用程序,因为每当套接字发送新数据时,它都必须呈现每个组件,因此触摸和搜索等事件需要大量时间来执行。[更新]事实证明我的应用程序正在渲染某些内容如果我删除了套接字连接,请查看更新 2

[问题:]我应该怎么做才能提高应用程序的性能?(比如不使用状态或使用 DOM 来更新我的应用程序等等)。

[更新 1:]我正在使用 https://github.com/irohitb/Crypto 这两个是 js 文件,所有逻辑都在其中发生 https://github.com/irohitb/Crypto/blob/master/src/container /cryptoContainer.js https://github.com/irohitb/Crypto/blob/master/src/components/CoinCard.js 我也从地图移动到平面列表。

[更新:2]我发现我的应用程序内部发生了无休止的渲染,这可能使我的线程忙碌(我的意思是它是无休止的并且不必要地传递props)。我在单独的Stackoverflow 线程上问了同样的问题,但没有得到正确的答复,因为它与性能有关,我想在这里悬赏。

请检查此线程:React 中的无限渲染

[答案更新:]虽然这里有很多很好的答案,但以防万一有人想了解它是如何工作的,您可以克隆我的存储库并返回到此提交之前我已将提交与我的问题解决的点联系起来(所以你可能需要回去看看我做错了什么)。此外,所有答案都非常有用且不难理解,因此您一定要仔细阅读。

4个回答

每次您的组件更新时,它都会启动一个新的套接字,这会导致内存泄漏,并会导致this.props.updateCrypto(updateCoinData);对同一数据多次调用。这可以通过打开componentDidMount()和关闭套接字来解决componentWillUnmount()

您还可以每隔几秒钟缓冲多个记录更新并一次性更改 FlatList 数据。

编辑,工作示例(App.js):

import React, { Component } from 'react';
import { Text, View, FlatList } from 'react-native';
import SocketIOClient from 'socket.io-client';

type Props = {};
export default class App extends Component<Props> {
    constructor(props) {
        super(props);

        this.currencies = {};
        this.state      = {
            currenciesList: [],
        }
    }

    componentDidMount() {
        this.socket = SocketIOClient('https://coincap.io');

        this.socket.on('trades', (tradeMsg) => {
            const time = new Date();

            // Store updates to currencies in an object
            this.currencies[tradeMsg.message.msg.short] = {
                ...tradeMsg.message.msg,
                time: time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds(),
            };

            // Create a new array from all currencies
            this.setState({currenciesList: Object.values(this.currencies)})
        });
    }

    componentWillUnmount() {
        this.socket.disconnect();
    }

    render() {
        return (
            <FlatList
                data={this.state.currenciesList}
                extraData={this.state.currenciesList}
                keyExtractor={(item) => item.short}
                renderItem={({item}) => <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                    <Text style={{flex: 1}}>{item.time}</Text>
                    <Text style={{flex: 1}}>{item.short}</Text>
                    <Text style={{flex: 1}}>{item.perc}</Text>
                    <Text style={{flex: 1}}>{item.price}</Text>
                </View>}
            />
        );
    }
}

有许多标准方法可以提高 React 应用程序的性能,最常见的是:

  • 使用通常的react优化(shouldComponentUpdate、PureComponent - 阅读文档)
  • 使用虚拟列表(限制数据的可见部分)

在这种情况下,我会添加:

在优化之前不要处理数据- fe 没有改变的格式化数据至少是不必要的。您可以插入中间组件(优化层),该组件将<CoinCard />仅在“原始数据”更改时传递/更新格式化数据

您可能不需要终极版当数据在同一个地方/结构简单,使用(在状态存储数据)。当然,您可以将 redux 用于其他全局共享的应用程序状态(fe 过滤选项)。

使用<FlatList />(react-native),找个更合适的?

更新

一些代码在平均时间(repo)被更改,此时(08.09)仍然存在一个问题并且可能导致内存泄漏。

您正在调用this.socket.on每个componentDidUpdate调用(错误编码的条件) - 不断添加新的处理程序!

componentDidUpdate() {
  // call all ONLY ONCE afer initial data loading
  if (!this.state.updateCoinData && !this.props.cryptoLoaded.length) {
    this.setState({updateCoinData: true}) // block condition
    this.socket.on('trades', (tradeMsg) => {

      // slice() is faster, new array instance
      // let updateCoinData = [...this.props.cryptoLoaded]; 
      let updateCoinData = this.props.cryptoLoaded.slice();

      for (let i=0; i<updateCoinData.length; i++) {
        //Search for changed Crypto Value
        if (updateCoinData[i]["short"] == tradeMsg.coin ) {

          // found, updating from message
          updateCoinData[i]["long"] = tradeMsg["message"]["msg"]["long"]
          updateCoinData[i]["short"] = tradeMsg["message"]["msg"]["short"]
          updateCoinData[i]["perc"] = tradeMsg["message"]["msg"]["perc"]
          updateCoinData[i]["mktcap"] = tradeMsg['message']['msg']["mktcap"]
          updateCoinData[i]["price"] = tradeMsg['message']['msg']['price']

          //Update the crypto Value state in Redux
          this.props.updateCrypto(updateCoinData);

          // record found and updated, no more looping needed
          break;
        }
      }
    })
  }
}

小错误:初始获取状态在减速器中设置为 true。

搜索性能问题我会看<CoinCard />

  • 使其成为 PureComponent;
  • increased并且decreased不需要保存在强制不必要的渲染调用的状态;
  • 我将使用更新时间(未保存在状态中,仅作为父项中的props传递,仅用于更新的行,在updateCoinData上面的代码中)并导出方向(检查 0 和仅符号)差异(已在 中计算perc仅适用于可见项目(来自渲染)并且仅在时间限制期间(渲染时间和数据更新props之间的差异)。setTimeout也可以使用。
  • 最后删除componentWillReceivePropscomponentDidUpdate并且shouldComponentUpdate应该(高度?)提高性能;

就像 Bhojendra Rauniyar 所说的,你应该在 CoinCard 中使用 shouldComponentUpdate。您可能还想更改您的 FlatList,您缩小的样本在 ScrollView 中有 FlatList,这会导致 FlatList 完全展开,从而一次呈现所有项目。

class cryptoTicker extends PureComponent {

      componentDidMount() {
        this.socket = openSocket('https://coincap.io');
        this.props.fetchCoin()
        this.props.CurrencyRate()

        this.socket.on('trades', (tradeMsg) => {

            for (let i=0; i< this.updateCoinData.length; i++) {

                if (this.updateCoinData[i]["short"] == tradeMsg.coin ) {

                    //Search for changed Crypto Value
                    this.updateCoinData["short"] = tradeMsg["message"]["msg"]["short"]
                    this.updateCoinData[i]["perc"] = tradeMsg["message"]["msg"]["perc"]
                    this.updateCoinData[i]["price"] = tradeMsg["message"]['msg']['price']

                    //Update the crypto Value state in Redux
                    this.props.updateCrypto(this.updateCoinData);

                }
            }
        })

      }

      componentWillReceiveProps(newProps){
        // Fill with redux data once
        if (this.updateCoinData.length < 1 && newProps.cryptoLoaded) {
            this.updateCoinData = [...newProps.cryptoLoaded];
        }
      }

    render() {

        return (
            <View style={{height: '100%'}}>
                <Header/>
                <FlatList
                    style={{flex:1}}
                    data={this.props.cryptoLoaded}
                    keyExtractor={item => item.short}
                    initialNumToRender={50}
                    windowSize={21}
                    removeClippedSubviews={true}
                    renderItem={({item, index}) => (
                        <CoinCard
                            index={index}
                            {...item}
                        />
                    )}
                />
            </View>
        )
    }
}

class CoinCard extends Component {

    shouldComponentUpdate(nextProps) {
        return this.props.price !== nextProps.price || this.props.perc !== nextProps.perc
    }

    render() {
        console.log("here: " + this.props.index);

        return (
            <View>
                <Text> {this.props.index} = {this.props.long} </Text>
            </View>
        )
    }
}

渲染 Flatlist 时,您应该考虑仅在需要时使用PureComponent或利用shouldComponentUpdate钩子进行更新。

文档

如果您的应用程序呈现长数据列表(数百或数千行),我们建议使用称为“窗口化”的技术。这种技术在任何给定时间只渲染一小部分行,并且可以显着减少重新渲染组件所需的时间以及创建的 DOM 节点的数量。

深入了解本性能指南

如果您仍然想要一些高级浏览,那么我建议您查看以下主题:

FlatList 和 VirtualizedList Scroll 性能在 30 多行后滞后

使用大列表时react的性能问题