反应本机性能问题 [英] React native performance issue

查看:62
本文介绍了反应本机性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using coincap api's to first fetch Data of about 1500+ crypto currency and then Web-socket to update the updated value of crypto Currency.

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

I a using redux to manage my state here

在我的 componentDidMount() 中,我调用了一个 redux action fetchCoin 来获取硬币的价值

Inside My componentDidMount(), I am calling a redux action fetchCoin which fetches the value of the coin

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

然后在 return 我正在做这样的事情

And then In return I am doing something like this

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

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

Then I have a web-socket which updates the value of cryptocurrency like this

 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

Now, While this work, the problem is that this is slowing my app like hell since whenever the socket sends new data, it has to render every component and hence events like touch and search takes lot of time to execute. [Update] It turns out my app is rendering something even If i remove socket connection, check out update 2

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

[Question:] What should I do so that I can improve the performance of App? (Something like not using state or using DOM to update my app and so on).

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

[Update 1:] I am using https://github.com/irohitb/Crypto And these two are js files where all the logic is happening https://github.com/irohitb/Crypto/blob/master/src/container/cryptoContainer.js https://github.com/irohitb/Crypto/blob/master/src/components/CoinCard.js I have also move from map to Flatlist.

[更新:2]我发现我的应用程序中有不断的渲染,这可能使我的线程忙碌(我的意思是它是无休止的& 不必要地传递道具).我在单独的 Stackoverflow 线程 上问了同样的问题,但没有收到正确的回复,因为它和性能有关,我想在这里悬赏一下.

[Update: 2] I found that there are endless render happening inside my App which is probably keeping my thread busy (I mean it is endless & unnecessarily passing props). I asked the same question on separate Stackoverflow thread but didn't received a proper response and since it is related to performance, I thought about putting a bounty on it here.

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

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

[Answer Update:] While there are many great answers here, Just in case someone wants to understand how it worked, You could probably clone my repository and go back to before this commit. I have linked the commit to the point where my problems was solved (so you might need to go back and see what I was doing wrong). Also, All the answers were very useful and not hard to comprehend so you should definitely go through them.

推荐答案

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

Like Bhojendra Rauniyar said, you should use shouldComponentUpdate in CoinCard. You probably also want to change your FlatList, your downsized sample has the FlatList in a ScrollView, this causes the FlatList to fully expand, thus rendering all it's items at once.

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

这篇关于反应本机性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆