In nearly all conversations about data and React, Props and State are the two most common concepts. However, I've noticed that there is technically a third way of setting data in a React component. More specifically, you can set a value by setting a value to this
.
For example, the code below I have set three values. One value on State, one value in the default Props, and the other on this
. I can print all three of them.
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
stateSecret: "foo"
};
this.otherSecret = "bar";
}
render() {
return (
<div className="App">
{this.state.stateSecret}
<br />
{this.otherSecret}
<br />
{this.props.propsSecret}
</div>
);
}
}
App.defaultProps = {
propsSecret: "baz"
};
export default App;
In general, I want to know if I am I committing to an anti-pattern by setting a value to this
. Is this something I should avoid?
No it's not an anti-pattern, it's generally okay.
If it's a constant you can even define it outside (4th way :D) like:
const otherSecret = "bar";
class App extends Component {
}
Generally speaking:
Define it in the state if it will change by some logic defined in your component
Define it in the parent and pass as prop if it will change by a logic defined in the parent
One more thing to consider, when the value of a prop or state changes, the component triggers a change and it runs the render() again, so if you want to reflect the changes, you should declare it in the state or as a prop from the parent component.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.