简体   繁体   English

React, JS - setState() 的最佳实践

[英]React, JS - best practices for setState()

I'm new to JS and React.我是 JS 和 React 的新手。 Went through the documentation given for setState() and found this here :浏览了为setState()提供的文档,并在这里找到了这个:

For better perceived performance, React may delay it, and then update several components in a single pass.为了获得更好的感知性能,React 可能会延迟它,然后一次更新多个组件。 React does not guarantee that the state changes are applied immediately. React 不保证状态更改会立即应用。
setState() does not always immediately update the component. setState()并不总是立即更新组件。 It may batch or defer the update until later.它可能会批量更新或推迟更新。

How exactly does it decide which components are to be updated immediately and which are to be deferred?它究竟如何决定哪些组件要立即更新,哪些要推迟?

More precisely, I have something similar to what is given below... Is it a bad idea to have one common setState() outside and another one depending on the conditions?更准确地说,我有一些类似于下面给出的东西......根据条件在外面有一个公共setState()和另一个是一个坏主意吗? Would it be better performance-wise to do the second option given below even if it means that there'd be a repetition of code?执行下面给出的第二个选项是否会更好的性能,即使这意味着会有重复的代码?

// First

this.setState({msg: 'Hello!'});

if (someCondition) {
  this.setState({
    res: true
  });
} else {
  this.setState({
    res: false
  });
}


// Second

if (someCondition) {
  this.setState({
    msg: 'Hello!'
    res: true,
  });
} else {
  this.setState({
    msg: 'Hello!'
    res: false,
  });
}

You could just do something like:你可以这样做:

this.setState({res: !!someCondition})

and if it is dependent upon a state value:如果它依赖于状态值:

this.setState(prevState => ({ res: !!prevState.someCondition })

setState() is async ; setState() 是异步的 those two code blocks will run similarly , since react will batch setStates for optimization;两个代码块的运行方式类似,因为 react 会批量设置 setState 以进行优化; So think about the code readability and maintainability ;所以要考虑代码的可读性可维护性 even though if it was different ( which is not ) you should prefer more readability over mere performance difference which is not even measurable;即使它不同(不是),您也应该更喜欢可读性,而不是仅仅无法衡量的性能差异; and always keep this in mind when trying new framework or langauage or anything.. premature optimization is the root of all evil并在尝试新框架或语言或任何东西时始终牢记这一点......过早的优化是万恶之源

From my opinion first would be better because setState will always recieve full new object not and existing one.在我看来,首先会更好,因为 setState 将始终收到完整的新对象而不是现有对象。 So changing one value will be better.所以改变一个值会更好。 I am also beginner but i will prefer first or i will use triple dots ie '{...this.state}' to get copy of existing state.我也是初学者,但我会更喜欢先或者我会使用三个点,即 '{...this.state}' 来获取现有状态的副本。

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

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