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