我有一个具有某些属性的对象,例如
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>)
所有属性名称在破坏过程中仍应写两次,这是一件好事。这允许仅从对象中选择已知属性。如果某些使用的道具未破坏或拼写错误,则将丢弃错误。如果没有偶然使用某些破坏性的道具,则可以用IDE或Linter表示。
这是不安全的,因为它使用eval
函数,但是您可以做这样的事情:
const Weather = ({ weather }) => {
eval(
"var " +
Object
.keys(weather)
.map(key => key + "="+ JSON.stringify(weather[key]))
.join(', '));
return (<div>
{name}, {location},
{anyAttribute.join(', ')}
</div>
)
};
ReactDOM.render(
<Weather weather={{
name: "lalala",
location: "dadada",
anyAttribute: [1,2,3]}} />,
document.getElementById("root")
);