Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extends state react

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
    )
  }
}
like image 828
Kovich Avatar asked Aug 09 '18 12:08

Kovich


People also ask

What is extends in React?

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.

How do you update state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.

What is componentWillMount in React?

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.


Video Answer


2 Answers

You can extend state as follows:

constructor(props) {
  super(props)

  this.state = {
    ...this.state,
    extraStuff: '',
  }
}
like image 118
haxpanel Avatar answered Oct 16 '22 16:10

haxpanel


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>
like image 4
Tholle Avatar answered Oct 16 '22 17:10

Tholle