我使用 coincap api 首先获取大约 1500 多种加密货币的数据,然后使用 Web-socket 来更新加密货币的更新值。
我在这里使用 redux 来管理我的状态
在我里面componentDidMount()
,我正在打电话还原动作 fetchCoin
获取硬币的价值
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)}
/>
然后我有一个网络套接字,它可以像这样更新加密货币的值
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);
}
}
})
}
现在,虽然这项工作有效,但问题是这会减慢我的应用程序的速度,因为每当套接字发送新数据时,它都必须渲染每个组件,因此触摸和搜索等事件需要花费大量时间来执行。[Update]事实证明,即使我删除套接字连接,我的应用程序也会呈现一些内容,查看更新 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/container/cryptoContainer.js
https://github.com/irohitb/Crypto/blob/master/src/components/CoinCard.js https://github.com/irohitb/Crypto/blob/master/src/components/CoinCard.js我也从地图转移到平面列表。
[更新:2]我发现有无尽的渲染发生在我的应用程序内,这可能使我的线程忙碌(我的意思是它是无止尽的和不必要的传递道具)。我在单独的地方问了同样的问题堆栈溢出线程 https://stackoverflow.com/questions/52213596/infinite-render-in-react但没有收到适当的回复,因为这与性能有关,所以我考虑在这里给予奖励。
请检查此线程:React 中的无限渲染 https://stackoverflow.com/questions/52213596/infinite-render-in-react
[答案更新:]虽然这里有很多很好的答案,但以防万一有人想了解它是如何工作的,您可以克隆我的存储库并返回before this commit https://github.com/irohitb/Crypto/commit/f395c7cda912599049d3448204a2b8a5660d6cb0。我已将提交链接到解决问题的位置(因此您可能需要返回并查看我做错了什么)。此外,所有答案都非常有用且不难理解,因此您绝对应该仔细阅读它们。