nico
30 Mar 2022
React js
Hello I need to use the the state in one class component for the react sortable tree.
But I use axios, thunk and redux to get the data.
So what is the best way to get the result of redux store data updated by ajax with axios to the state of my class component each time ?
Basically each time i click “search” it will send action to redux which updates the store, I need then a good way to update the component state from the store.
Thanks for your advice.
nico
30 Mar 2022
As far as I am concerned there are two ways:
- getDerivedStateFromProps : which allows us to return the new state from the new prop
state = {
MyData: xxx
}
static getDerivedStateFromProps(props, state) {
return {
MyData: props.MyData,
};
}
I don't really like it as it is static and we can't use anything in my class component…
- componentDidUpdate : which allows us to get the new props and we can compare with the previous props, then we can use this.setState()
componentDidUpdate(props) {
const { MyData } = this.props
if (props.MyData !== MyData ) {
this.setState({ MyData : props.MyData }))
}
}
It is not perfect as we need to setState which calls render again.. so it s less smooth and for performance reason it is a shame too
nico
31 Mar 2022
Thanks for your feedback :)
© 2024 Copyrights reserved for web-brackets.com