- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 367字
- 2021-08-13 15:13:02
Using HOCs instead
I believe that you can easily translate the preceding use case into HOC. Let's do this together, and then we will discuss why HOCs are better:
// Chapter 2_View patterns/ Example 13/ App.js
const withLogger = (ComponentToEnrich, logText) =>
class WithLogger extends React.Component {
componentDidMount = () => console.log(
logText || 'Component has been rendered successfully!'
);
render = () => <ComponentToEnrich {...this.props} />;
};
const App = () => (
<View style={styles.container}>
<Text>Some text in a component with mixin.</Text>
</View>
);
export default withLogger(withLogger(App), 'Some other log msg');
The first thing you will immediately spot is that HOCs stack on top of each other. HOCs literally compose with each other. This is much more flexible and protects you from name clashes that may happen when using Mixins. React developers mention the handleChange function as a problematic example:
"There is no guarantee that two particular mixins can be used together. For example, if FluxListenerMixin defines handleChange() and WindowSizeMixin defines handleChange(), you can’t use them together. You also can’t define a method with this name on your own component.
It’s not a big deal if you control the mixin code. When you have a conflict, you can rename that method on one of the mixins. However, it’s tricky because some components or other mixins may already be calling this method directly, and you need to find and fix those calls as well."
- Official React blog post by Dan Abramov (https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html).
Additionally, Mixins may lead to adding more and more state. Looking at the preceding examples, it may appear that HOCs do the same, but in fact, shouldn't. This is an issue that I struggle with in the React ecosystem. It gives you a lot of power and you may not realize that the patterns you begin to use are so-so. To me, stateful components should be rare, and so should stateful HOCs. In this book, I will teach you how to avoid using state objects in favor of a better solution that decouples state from your components as much as possible. We will learn about this further in Chapter 5, Store Patterns.
- Flask Web全棧開發(fā)實(shí)戰(zhàn)
- Oracle WebLogic Server 12c:First Look
- SQL Server 2012數(shù)據(jù)庫技術(shù)及應(yīng)用(微課版·第5版)
- Java Web及其框架技術(shù)
- Wireshark Network Security
- Internet of Things with Intel Galileo
- Mastering Python Networking
- Symfony2 Essentials
- 小學(xué)生C++創(chuàng)意編程(視頻教學(xué)版)
- Mastering JavaScript Design Patterns(Second Edition)
- Tableau 10 Bootcamp
- JavaScript應(yīng)用開發(fā)實(shí)踐指南
- Swift High Performance
- ASP.NET Core and Angular 2
- 精益軟件開發(fā)管理之道