gpt4 book ai didi

javascript - React 和 es6 中更好的对象解构

转载 作者:行者123 更新时间:2023-11-30 15:21:10 26 4
gpt4 key购买 nike

我有一个具有一些属性的对象

weather.name = 'Coudy'
weather.country= 'USA'

目前我在 ES6 中使用对象解构,但如您所见,它非常冗长。我想知道是否可以用更简洁的方式重写这段代码。

注意:我正在使用 babel

  "presets": ["es2015", "react", "stage-2"]

const Weather = ({ weather }) => {
let {
name,
country,
temperature,
temperatureMin,
temperatureMax,
weatherMain,
weatherDescription,
weatherIcon,
updatedTime,
windDegree,
windSpeed,
visibility
} = weather
return (<div>
{ name }, { country }
{ temperature }
{ temperatureMin }
{ temperatureMax }
{ weatherMain }
{ weatherDescription }
{ weatherIcon }
{ updatedTime }
{ windDegree }
{ windSpeed }
{ visibility }
</div>
)
}

export default Weather

最佳答案

是的,参数解构是可能的。可以有效地跳过 weather 临时变量(还有 Weather - 它无论如何都不是构造函数):

export default ({ weather: {
name,
country,
temperature,
temperatureMin,
temperatureMax,
weatherMain,
weatherDescription,
weatherIcon,
updatedTime,
windDegree,
windSpeed,
visibility
} }) => (<div>
{ name }, { country }
{ temperature }
{ temperatureMin }
{ temperatureMax }
{ weatherMain }
{ weatherDescription }
{ weatherIcon }
{ updatedTime }
{ windDegree }
{ windSpeed }
{ visibility }
</div>)

所有的属性名在解构过程中仍然应该写两次,这是一件好事。这允许仅从对象中选取已知属性。如果一些使用过的 Prop 没有被解构或在返回值中拼写错误,则会抛出错误。并且如果一些被解构的 props 没有被意外使用,这可以通过 IDE 或 linter 来指示。

关于javascript - React 和 es6 中更好的对象解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706866/

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