Can't call setState on a component that is not yet mounted
This warning that you are getting is because you are setting a reference to clickMe method in the constructor, which is then using the setState().
constructor (props) { super(props) this.state = { initial: 'state', some: '' } this.clickMe = this.clickMe.bind(this); <--- This method } clickMe () { this.setState({ some: 'new state' <-- the setState reference that is causing the issue }) }
Try removing the this.clickMe = this.clickMe.bind(this) from constructor and do it in a lifecycle method like componentWillMount() or ComponentDidMount(). For react 16 and above you can use the componentWillMount method with "SAFE_" prefix. [SAFE_componentWillMount]
componentWillMount() { this.clickMe = this.clickMe.bind(this); }clickMe () { this.setState({ some: 'new state' }) }
Just add following line to your code
export default class MyComponent extends React.Component { constructor (props) { super(props) this.state = { initial: 'state', some: '' // <------- THIS LINE } this.clickMe = this.clickMe.bind(this) } clickMe () { this.setState({ some: 'new state' }) } render () { return ( <div> <button onClick={this.clickMe}>click</button> </div> ); }}
You just need to use the componentDidMount()
method. As the React documentation tells in the component life cycle, if you need to load data from a remote endpoint, this is a good place to instantiate the network request and you may call setState()
immediately in componentDidMount()
.
Like this:
componentDidMount(){ this.clickMe = this.clickMe.bind(this);}clickMe () { this.setState({ some: 'new state' })}