React render中的销毁状态 [英] Destructuring state in React render

查看:249
本文介绍了React render中的销毁状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多示例,这些示例显示了一个类似于以下内容的React组件:

I see a lot of examples that show a React component that looks like this:

class MyComponent extends Component {
   constructor(props) {
     super(props)

     this.state = {
       foo: 'foo',
       bar: 'bar'
     }
   }

   render() {
     const { foo, bar } = this.state

     return <Text>{foo}{bar}</Text>
   }
}

如您所见,组件的状态已被破坏.我可以看到JSX看起来更干净,但是似乎很难知道变量来自组件状态.就最佳实践而言,这样做有什么好处吗?还是只是偏爱?

As you can see, the component's state has been destructured. I can see that the JSX looks cleaner, but it appears that it would be harder to know that a variables came from the components state. Is there any benefit of doing this in terms of best practices or is it just a preference?

谢谢.

推荐答案

优点:代码看起来更加简洁,尤其是当您需要在组件中多次重用状态值时.

Advantage: The code looks much cleaner especially if you need to reuse state values multiple times in a component.

缺点::如果您要制作模块或开放源代码,则破坏语句可能会造成混乱.

Disadvantage: If you're making a module or open sourcing your code the destructed statement could cause confusions.

这篇关于React render中的销毁状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆