I need to inherit the state. Can I inherit the state? When I do this, I get an empty state.
class Example extends Component {
constructor(props) {
super();
this.state = {
param1:
};
}
...
}
class Example2 extends Example {
render() {
return (
{this.state.param1} // empty
)
}
}
Implement Inheritance in React Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass.
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.
The componentWillMount() lifecycle hook is primarily used to implement server-side logic before the actual rendering happens, such as making an API call to the server. In this guide, you will learn to use componentWillMount() and make API calls after the initial component rendering.
You can extend state as follows:
constructor(props) {
super(props)
this.state = {
...this.state,
extraStuff: '',
}
}
Instead of using inheritance, you could use regular composition and pass the entire Example
state as props to Example2
and use the props passed to Example2
as initial state.
Example
class Example extends React.Component {
state = {
param1: "test"
};
render() {
return <Example2 {...this.state} />;
}
}
class Example2 extends React.Component {
state = {...this.props};
render() {
return <div>{JSON.stringify(this.state)}</div>;
}
}
ReactDOM.render(<Example />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With