简体   繁体   English

当状态项不是集合时,在React中设置状态的正确方法

[英]Correct way to setState in React when item in state is not a collection

I'm working with realtime financial data such as equities and precious metal prices. 我正在处理股票和贵金属价格等实时财务数据。 I'm hitting an API every few seconds to grab the latest price for a given asset and storing that price in state. 我每隔几秒钟就会命中一次API,以获取给定资产的最新价格并将该价格存储在状态中。 However, I've always updated state with an array or array of objects, but this data is just a string. 但是,我总是用一个数组或对象数组更新状态,但是此数据只是一个字符串。 If the latest GET request returns a different value than what is currently set then overwrite the value. 如果最新的GET请求返回的值不同于当前设置的值,则覆盖该值。

I'm just wondering what best practices are for updating a simple string in state? 我只是想知道更新状态中的简单字符串的最佳实践是什么?

my state constructor: 我的状态构造函数:

this.state = {
  goldPrice: '',
  items: {}
}

My API request: 我的API请求:

fetchGoldPrice() {
  jQuery.ajax({
    method: 'GET',
    headers: {'Access-Control-Allow-Origin': '*'},
    url: Constants.API_URL,
    success: (gold) => {
      this.updateGoldPrice(gold.gold_bid_usd_toz);
    }
  });
}

If successful the fetch calls updateGoldPrice and passes in the price that was returned. 如果成功,则获取将调用updateGoldPrice并传递返回的价格。

updateGoldPrice(goldPrice) {
  this.setState({ goldPrice: goldPrice });
}

And then I check the price every 30 seconds: 然后我每30秒检查一次价格:

componentDidMount() {
  this.fetchGoldPrice();
  this.timer = setInterval(
    () => this.fetchGoldPrice(), 30000);
}

I'm just curious if this is an alright way to do this. 我很好奇这是否是一种好的方法。 Because everything I read says to do something like this: 因为我阅读的所有内容都表示要执行以下操作:

addItem(item) {
  const items = {...this.state.items};
  items[item] = item;
  this.setState({ items: items });
}

But I'm not storing all the prices in an array, I just want the single latest price. 但是我没有将所有价格存储在一个数组中,我只想要一个最新价格。

Thank you. 谢谢。

Well the best practice you are referring to is Never mutate the state! 那么,您指的最佳实践是永不改变状态! .
In your case, string is a primitive type (primitive value actually), thus its already immutable by default so no worries here. 在您的情况下, string是原始类型(实际上是原始值),因此默认情况下它已经是不可变的,因此在此无需担心。
You need to look out from reference types like Array & Object . 您需要注意诸如ArrayObject引用类型。

Primitive Types (6 as of ES6 ): 基本类型(截至ES6 6种):

Boolean
Null
Undefined
Number
String
Symbol (new in ECMAScript 6)

You are doing this correctly. 您正在正确执行此操作。 Your UI only displays the latest price so that's all you need to store in your state. 您的用户界面仅显示最新价格,因此您只需要在该州存储即可。 No need to store historical prices if you're not displaying them. 如果您不显示历史价格,则无需存储它们。

Furthermore, storing primitive types in your state this.setState({foo: "bar"}) is completely fine. 此外,在您的状态下存储基本类型this.setState({foo: "bar"})完全可以。

The recommended way as per react documentation is to use the setState method from the react libray.. using this method . 根据react文档的推荐方法是使用react libray中的setState方法。 is by "setState({MyStateToModify: "new value"}). Hope that can help you 是通过“ setState({MyStateToModify:“新值”}})。希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM