React Tutorial: Props Anti-Pattern
In the article Passing Props , we learned about the concept of React Props and how to use it. In this article, we will introduce the use of Props to generate state in getInitialState. This method of use is called Anti-Pattern.
The reason why it is called an anti-pattern is that using Props to generate state in getInitialState will cause repeated "source trust" problems. In addition, the getInitialState function is only called when the component is rendered for the first time. That is to say, when the component is rendered for the second time, the getInitialState function will not be called again. That is to say, if we want to change the value of Props and thus the value of State through the second rendering, it is impossible.
Let's look at a piece of code:
var MessageBox = React.createClass({
getInitialState: function() {
return {name: 'Mr. ' + this.props.name};
},
render: function() {
return <div>{'Mr. '+this.state.name}</div>;
}
});
ReactDOM.render(
<MessageBox name="Rogers" />,
document.getElementById('content')
);
The above example is an anti-pattern. If we want to render the MessageBox component again and change the name value of Props, we will find that the content in the div remains unchanged, and it is still Mr. Rogers instead of Mr. Onmpw.
ReactDOM.render(
<MessageBox name="Rogers" />,
document.getElementById('content')
);
ReactDOM.render(
<MessageBox name="Onmpw" />,
document.getElementById('content')
);
So, for the above example, it is better to use this.props directly in div rather than this.state.
var MessageBox = React.createClass({
render: function() {
return <div>{'Mr. '+this.props.name}</div>;
}
});
ReactDOM.render(
<MessageBox name="Onmpw" />,
document.getElementById('content')
);
The result of this example is Mr. Onmpw output on the page.
ReactDOM.render(
<MessageBox name="Rogers" />,
document.getElementById('content')
);
If we render again, it will be Mr. Rogers.
The situation described above is an anti-pattern of using Props in getInitialState. Of course, if we can clearly define the purpose of Props , using it in getInitialState will not produce anti-patterns. For example, when a value is initialized, the value of the Prop will not change.
var Counter = React.createClass({
getInitialState: function() {
return {count: this.props.initialCount};
},
handleClick: function() {
this.setState({count: this.state.count + 1});
},
render: function() {
return <div onClick={this.handleClick}>{this.state.count}</div>;
}
});
ReactDOM.render(
<Counter initialCount={7}/>,
document.getElementById('content')
);
The above examples avoid the anti-pattern. The above examples are modified from the examples in the official documentation. I hope this article will help you learn React .
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
Rendered fewer hooks than expected error in React
Publish Date:2025/03/16 Views:50 Category:React
-
When we use a hook after a condition that may return a value, we get the error "Rendered fewer hooks than expected. This may be caused by an accidental early return statement". To fix this error, you need to move all React hooks to any condition that
Fix Uncaught ReferenceError: useState is not defined in React
Publish Date:2025/03/15 Views:142 Category:React
-
When we use the useState hook in our code but forget to import it, it generates the error Uncaught ReferenceError: useState is not defined. To fix this error, you need to import the hook before using it import {useState} from react . // ?️
React error Uncaught ReferenceError: process is not defined solution
Publish Date:2025/03/15 Views:117 Category:React
-
To resolve the “Uncaught ReferenceError: process is not defined” error in React, open a terminal in the root directory of your project and update the version of the `react-scripts` package by running `npm install react-scripts@latest` and reinstal
How to solve the "Function components cannot have string refs" error in React
Publish Date:2025/03/15 Views:139 Category:React
-
When we use a string as a reference in a function component, we get the error "Function components cannot have string refs". To fix this error, we need to use the useRef() hook to get a mutable ref object that we can use as a component.
React Error Property 'X' does not exist on type 'Readonly<{}>'
Publish Date:2025/03/15 Views:140 Category:React
-
The React.js error “Property does not exist on type 'Readonly'” occurs when we try to access the props or state of an untyped class component. To fix the error, you need to use generics on the React.Component class to type the props or state of th
Solve React's Unexpected default export of anonymous function error
Publish Date:2025/03/15 Views:120 Category:React
-
When we try to export an anonymous function using default export, it results in the warning “Unexpected default export of anonymous function.” To fix this error, you need to give the function a name before exporting it.
React error Type '() => JSX.Element[]' is not assignable to type FunctionCompo
Publish Date:2025/03/15 Views:52 Category:React
-
When we try to return an array of elements from a function component, a React.js error “Type '() => JSX.Element[]' is not assignable to type FunctionComponent” occurs. To fix the error, you need to wrap the array of elements in a React fragment.
How to solve React Type {children: Element} has no properties in common with type
Publish Date:2025/03/15 Views:104 Category:React
-
React.js error "Type {children: Element} has no properties in common with type IntrinsicAttributes" occurs when we try to pass children prop to a component without any props. To resolve the error, you need to define and type the properties on the comp