简体   繁体   English

在React解包“this”是不好的做法吗?

[英]Is it bad practice to unpack “this” in React?

I always unpack this so that the render function looks tidier. 我总是解开使得渲染功能看起来更整洁。 Is it bad practice to do this? 这样做是不好的做法?

Example: 例:

class Zoom extends React.Component {
    // ...

    render() {
        const {view, zoomOutScreen} = this;
        const {navigation} = this.props;

        return (
            <Wrapper
                innerRef={view}
                animation='zoomIn'
                duration={200}
                useNativeDriver={true}
            >
                <Component
                    navigation={navigation}
                    zoomOutScreen={zoomOutScreen}
                />
            </Wrapper>
        );
    }
}

It's neither good nor bad, it's primarily a matter of style. 这既不好也不坏,主要是风格问题。

There could be a very small objective difference in some usage scenarios, but nothing worth thinking about. 在某些使用场景中可能存在非常小的客观差异,但没有什么值得考虑的。 (If you use the properties repeatedly, caching them to a local constant may make them faster to look up. If you don't, caching them to a local constant is an unnecessary step. But again, in 99.999999999% of cases, it's just not going to make any real-world difference at all. Do what seems clearest.) (如果重复使用这些属性,将它们缓存到局部常量可能会使它们更快查找。如果不这样做,将它们缓存到局部常量是不必要的步骤。但同样,在99.999999999%的情况下,它只是根本不会产生任何现实世界的差异。做一些看起来最清楚的事情。)


Side note: If you want, you can combine your two destructuring assignments: 附注:如果需要,您可以结合两个解构分配:

const {view, zoomOutScreen, props: {navigation}} = this;

Not a bad practice but it is more code-readability and avoiding anti-patterns in React. 这不是一个糟糕的做法,但它更具代码可读性并避免了React中的反模式。 It gives the knowledge to user what objects are binded to this component and what else is referring to global objects. 它为用户提供了哪些对象绑定到此组件以及其他什么是指全局对象的知识。 So It it preferable not to destruct it. 所以最好不要破坏它。

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

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