[英]React-router Pass Data
我正在為我的項目使用React。 我也在使用react-router-dom庫。 但是,我對使用react-router-dom傳遞數據感到困惑。
這是父組件的代碼:
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>
);
}
}
它有一個名為Path的狀態。 Parent Component將onChangeLanguage函數傳遞給其Child組件。
這是兒童組件:
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>
);
}
}
如果單擊Child Component中的Change Lanuguage
按鈕,則調用該函數並更改Parent Component中的狀態。 支持LanguageChosen
也在Child組件中更新。
但是,如果我刷新頁面,如果按下按鈕,則不會更新Child中的道具LanguageChosen
。 它只能工作如果我不刷新頁面。
我應該如何解決這個問題。 謝謝!
你遇到這個問題的原因就在這里
const { languageChosen } = this.props.location.state
languageChose是從this.props.location設置的,當url更改為“/ child / id /:id”時設置位置,刷新頁面后,在parent元素更改狀態,但不會更改location.state.And ,我認為你可以在組件中使用道具來解決問題。 1.在路線中設置languageChosen屬性
component={props => (
<Child {...props} onChangeLanguage={this.onChangeLanguage} languageChosen={this.state.Path.state.languageChosen}/>
)}
2.在子組件中更改此項
const { languageChosen } = this.props.languageChosen;
這段代碼讓我感到困惑,但是,請記住,當您刷新頁面時,所有的javascript都會被重新加載,因此您在父級中將languageChosen
硬編碼為English
,因此每次刷新頁面時都會重置為English
。 您可以將值存儲在localStorage中並在刷新時檢查它是否存在,或者將其添加到路徑路徑child/id/:id/:language
然后,如果您使用的是React Router v4,請在您的子組件中使用this.props.match.params.language
,它將呈現給定的語言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.