How to Force Props to Be Passed Down Again From a Parent React
Annotation: Every bit of React xvi, componentWillReceiveProps() is deprecated, meaning if you are using that version or college in your project, this is not good advice for yous.
In the React world, forcing a re-return is frowned upon. You should let the DOM take care of itself when React perceives changes to state or props. In order to follow these patterns, nosotros sometimes accept to exercise stuff that seems a piffling silly. Consider this scenario:
We've got two components — a parent and a kid. The parent makes an API call to fetch the user. From that, we go things like name, age, favorite color. We besides get an id from our database. We'll laissez passer that to our child component, which is also going to make an API call, with the user id. Awesome — lots of information coming into our app.
Let's say we are storing a list of shoes in the database. When the user changes their color preference, the server writes new data to the user's shoe list. Slap-up! Except, we aren't seeing the new shoe list in our child component. What gives?
Side note: Of course we should just go the shoes from the call for the user — this is merely a simplified explanation.
React rerendering nuts
The brusk of it is that React will only update parts of the DOM that have changed. In this case, the props we laissez passer to the shoe component ( userId) oasis't inverse, so nothing changes in our child component.
The colour preference for the user will update when we get back new information from the API — assuming we are doing something with the response after nosotros update a user.
But every bit React sees no reason to update the shoe listing, it won't — even though on our server, the shoes are at present different.
The starting code
const UserShow extends Component { state = { user: {} } componentDidMount() { this.fetchUser().then(this.refreshUser) } setNewColor = colour => { this.updateUser({color}).then(this.refreshUser) } refreshUser = res => this.setState({user: res.data.user}) render() { const { user } = this.country; return ( <div> User proper name: {user.name} Pick color: <div> {colors.map(colour => <div className={color} onClick={() => this.setNewColor(colour)} />)} )} </div> <ShoeList id={user.id} /> </div> ) } } Our ShoeList is merely going to exist a listing of shoes, which we'll fetch from the server with the user's id:
const ShoeList extends Component { state = { shoes: [] } componentDidMount() { this.fetchShoes(this.props.id) .and then(this.refreshShoeList) } refreshShoeList = res => this.setState({ shoes: res.data.shoes }) render() { // some list of shoes } } If we want the shoe component to grab the new list of shoes, we demand to update the props nosotros ship to it. Otherwise it will see no need to refresh.
In fact, the fashion this is written, the ShoeList would never refresh, as we are non dependent on props for rendering. Let's fix that.
Triggering a child component to re-render
To strength the child component to re-render — and make a new API telephone call — we'll need to pass a prop that will change if the user's color preference has inverse.
To do this, we'll add a method into setNewColor:
[...] setNewColor = color => { this.updateUser({color}).then(res => { this.refreshUser(res); this.refreshShoeList(); }) } refreshShoeList = () => this.setState({refreshShoeList: !this.country.refreshShoeList}) [...] <ShoeList id={user.id} refresh={refreshShoeList} This is a unproblematic switch we can flip. I've kept things as simple as possible, merely in production we'd desire to make certain that the color nosotros're setting is unlike than the color we had before. Otherwise, there will be nothing to update.
Now in the ShoeList:
componentWillReceiveProps(props) { const { refresh, id } = this.props; if (props.refresh !== refresh) { this.fetchShoes(id) .then(this.refreshShoeList) } } If yous pass only refreshShoeList and and so toggle based on that boolean, the component will just update forever and ever and ever.
Nosotros need to make sure the switch has flipped only once — then nosotros'll just check that the props coming in are different than the props we had before. If they are different, we'll brand a new API phone call to get the new listing of shoes.
And boom — our kid component has been "forced" to update.
componentWillReceiveProps
It'southward worth taking just one more minute to review what's going on in that concluding piece of code. In componentWillReceiveProps nosotros accept our only opportunity to view new props equally they are coming in and compare them with previous props.
Here nosotros can detect changes (like in refresh) and we can besides brand checks for new props (notation, for instance, that refresh is initially undefined).
This React method is a very powerful way to manipulate and examine props.
Acquire to code for free. freeCodeCamp's open up source curriculum has helped more than 40,000 people get jobs equally developers. Become started
Source: https://www.freecodecamp.org/news/force-refreshing-a-react-child-component-the-easy-way-6cdbb9e6d99c/
0 Response to "How to Force Props to Be Passed Down Again From a Parent React"
Postar um comentário