Is there a good way to use private variables and methods in React.js

I noticed that I can use private variables like this:

var Hello = React.createClass(new (function(){ var name; this.getInitialState = function() { name = "Sir " + this.props.name; return null; }; this.render = function() { return <div>Hello {name}</div>; }; })()); React.render(<Hello name="World" />, document.getElementById('container')); 

Why shouldn’t I do this?

Thanks for any help

+6
source share
3 answers

I do not think that something is wrong with this. The syntax is a bit funky, but it's a smart trick.

I would question the need for a truly private variable. I can only think of two reasons why someone might want them, but both can be debunked.

1) You make a library for others to consume ... If someone picks inside your library code where they shouldn't be, they either violate their own experience or work with errors that they found in your code. In any case, no harm to you or others. Worse, they violate their own application. Private variables left a very bad taste in the mouth coming from Flex. Open JavaScript is a breath of fresh air IMO.

2) You want to hide personal data inside your application ... With modern browsers, anything in JavaScript can be checked and changed at runtime. Unable to hide data from users in JavaScript. You can only complicate the search.

I know that this alternative is not really private, but the use is the same. Since I am not a big fan of the struggle to make something private, I’ll turn it on anyway .; D)

 var Hello = React.createClass({ name: null, getInitialState: function() { this.name = "Sir " + this.props.name; return null; }, render: function() { return <div>Hello {this.name}</div>; }; }); React.render(<Hello name="World" />, document.getElementById('container')); 
+2
source

If you use es7, you can define class properties as private variables, such as:

 class Hello extends React.Component { name = 'Jack'; render() { return ( <div> {this.name} </div> ); } } export default Hello; 

Be sure to use babel to compile your code with stage 0

+2
source

Private vars are ideal when you need local (closed) state information for a component that DOES NOT change or is directly related to visualization. Keep in mind that most things change rendering, so I found that I rarely use private vars.

Also, keep in mind when you add a variable to a class the way you did, its singleton, so it will be used by all instances of this component. This can lead to problems if you really need something personal for each instance - if this is what you want, then you need to declare it in one of the life cycle methods for the component, perhaps this type

 componentDidMount() { this.name = 'hello'; }, 
+1
source

All Articles