I think this solution may work only when the app is created using npx create-react-app
This solution is exemplified here
It is clear that this.setState
can only be called on a mounted or mounting component.
A mildly confusing situation I encountered was a this.setState
that was called from
inside of a componentDidMount
method and yet resulted in the afore-mentioned message.
Obviously that was because the the this.setState
was called from an asynchronous
callback, as in the following code:
componentDidMount: function() { $.getJSON(this.getURL(), function(data) { this.setState({files: data}); }.bind(this)); }What fixed that (according to the source) was simply doing a:
componentDidMount: function() { $.getJSON(this.getURL(), function(data) { if (this.isMounted()) { this.setState({files: data}); } }.bind(this)); }The source also provides an alternative solution which I think is cleaner: abort the asynchronous request in the
componentWillUnmount
method (assuming of course that
the network library you are using provides an abort API).
There are many resources on the subject that one can google about. For the benefit
of my future self I've put together a small example in my playground github repo that shows how to properly
use state. Bottom line is that state lives in the parent components and flows
down into the child components as properties. Also, state is not set upon
component initialization. The proper way to set state is with the setState
method
so that React can automatically call render
on the component whose state was altered.
Moreover the following guidelines are useful:
getInitialState
unless it is done only for seeding (in which case prefix the properties name with initial
to make the intention clear).
It is often the case when doing development in Webpack that you
have your, e.g. React JXS code running in the webpack development server
(the one you typically launch with npm run dev
) and you need
that front-end code to access via Ajax some back-end services, e.g. some
JAX-RS module deployed in a Tomcat container.
In those cases, one runs into CORS issues. To solve the problem you have to enable CORS on the backend module as described in this note.
I have created an archetype project to exemplify the full chain, from a React front-end application running in webpack development server to a back-end JAX-RS module deployed in a Tomcat container.