gpt4 book ai didi

reactjs - 为什么要在 React 中从 props 和 state 创建常量?

转载 作者:行者123 更新时间:2023-12-03 14:17:56 25 4
gpt4 key购买 nike

我在 React 代码中经常看到这种代码模式:

render() {
const units = this.props.units;
const temperature = this.state.temperature;

return (<p>{temperature} {units}</p>);
}

我问过的一些开发人员说,在渲染或其他函数中使用状态/属性之前将它们拉入本地常量是标准做法 - 但是,我找不到 React 文档中任何地方讨论的这种做法,并且这些文档中的示例代码有时只是直接访问 state/prop 属性。

我更喜欢使用直接访问,因为当您可以立即看到属性来自哪里而不必寻找本地常量定义时,它使代码更具可读性。

在我做出这个决定之前,我想知道是否有人知道为什么存在这种做法以及是否有充分的理由使用它?

上面的例子和这个有功能上的区别吗?

render() {
return (<p>{this.state.temperature} {this.props.units}</p>);
}

最佳答案

当函数内部要使用许多 Prop /状态时,拉动状态/ Prop 是一种标准做法

eg: const { prop1, prop2, prop3, prop4, ... } = this.props
const { state1, state2, state3, ... } = this.state

您现在可以使用常量名称来引用它们,而不是

this.props.propName/stateName everywhere.

您不应该在您提供的只有 1/少数 props/state 的示例中这样做

const units = this.props.units; // Not recommended

底线:只是更干净的代码。偏好问题。

关于reactjs - 为什么要在 React 中从 props 和 state 创建常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com