Reputation: 821
I am using React for my project. I am also using react-router-dom library. However, I am confusing about passing data by react-router-dom.
Here is code for Parent Component:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
Path: {
pathname: "/child/id/1",
state: {
languageChosen: "English"
}
}
};
this.onChangeLanguage = this.onChangeLanguage.bind(this);
}
onChangeLanguage() {
const { Path } = this.state
Path.state.languageChosen = 'Spanish'
this.setState({Path})
}
render() {
return (
<div>
<NavLink to={this.state.Path}>ToChild</NavLink>
<Route
path={`/child/id/:id`}
render={props => (
<Child {...props} onChangeLanguage={this.onChangeLanguage} />
)}
/>
</div>
);
}
}
It has a state called Path. The Parent Component pass function onChangeLanguage to its Child component.
Here is Child Component:
class Child extends Component {
onChange = () => {
this.props.onChangeLanguage;
};
render() {
const { languageChosen } = this.props.location.state;
return (
<div>
{languageChosen === "English" ? "English" : "Spanish"}
<button onClick={this.onChange}>Change Language</button>
</div>
);
}
}
If I click the Change Lanuguage
button in Child Component, the function was called and the state in Parent Component change. The prop LanguageChosen
also update in Child component.
However, if I refresh the page, the prop LanguageChosen
in Child doesn't update if I press the button. It only works If I don't refresh the page.
How should I fix that. Thanks!
Upvotes: 1
Views: 2377
Reputation: 2361
The reason that you get this problem is here
const { languageChosen } = this.props.location.state
languageChose is set from this.props.location,location is set when url change to "/child/id/:id",after refreshing the page,state in Parent element change, but it won't change the location.state.And,I think you can use props in component to solve the problem. 1. set a languageChosen property in route
component={props => (
<Child {...props} onChangeLanguage={this.onChangeLanguage} languageChosen={this.state.Path.state.languageChosen}/>
)}
2. change this in the Child component
const { languageChosen } = this.props.languageChosen;
Upvotes: 2
Reputation: 154
This code confuses me a bit but, remember when you refresh a page all the javascript gets reloaded, so you hard coded languageChosen
to English
in your Parent so every time you refresh the page it resets to English
. You can either store the value in localStorage and check for its existence on refresh, or add it to your route path child/id/:id/:language
Then if you are using React Router v4, in your child component use this.props.match.params.language
and it will render the given language.
Upvotes: 1