Reputation: 1760
I want to update state via ComponentWillMount()
like:
this.state = {
Canonical:''
}
componentWillMount(){
this.setState({Canonical: window.location.href})
}
Anybody have idea how to do that?
Upvotes: 2
Views: 14946
Reputation: 1354
If you want to setState while initializing then
constructor(props){
super(props);
this.state = {
Canonical : window.location.href
};
}
or if you want to update the state on componentWillMount then
constructor(props){
super(props);
this.state = {
Canonical : ''
};
}
componentWillMount(){
this.setState({ Canonical : window.location.href });
}
componentWillMount function will call before the render function. If something went wrong in componentWillMount the component won't render. it will block better you can try with componentDidMount(); function this function will be called after the render function in the component
Class Component{
//sample structure of component and the flow
componentWillMount(){}
render(){}
componentDidMount(){}
}
If you are using React Router then you can call it like : this.props.location
its a feature in that package
to know more : https://reacttraining.com/react-router/web/api/location
Upvotes: 0
Reputation: 930
You should use componentDidMount method. This lifecycle method is invoked after the mounting of component and the same time it invokes componentWillMount.
setting state re-renders the component.
Another option is you initialise the state value in constructor.
constructor(){
super();
this.state = {
Canonical: window.location.href
}
}
or
componentDidMount(){
this.setState({Canonical: window.location.href})
}
Upvotes: 2
Reputation: 6556
You should avoid async initialization in componentWillMount()
componentWillMount()
is invoked immediately before mounting occurs. It is called before render()
, therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.
Make async calls for component initialization in componentDidMount
instead of componentWillMount
function componentDidMount() {
axios.get(`api/messages`)
.then((result) => {
const messages = result.data
console.log("COMPONENT WILL Mount messages : ", messages);
this.setState({
messages: [...messages.content]
})
})
}
Note that
componentWillMount
is depreciated because it is not safe for async rendering
React: https://reactjs.org/docs/react-component.html#unsafe_componentwillmount
Good read: https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b
Upvotes: 0