用戶登錄後,我想在標題中顯示該名稱。我一直在閱讀如何傳遞道具,但是我看到的是當你從另一個組件訪問另一個組件狀態時,你再次發現了其他組件。如何在不渲染其他組件的情況下訪問另一個狀態?這裏,我並不想渲染標題組件洞察我的登錄組件,不知如何訪問另一個組件狀態而不呈現該狀態?
- 在這裏,我重定向這樣我就可以在該州通過的(但因爲我重定向到「/」作爲主成分,而不是標題組件,我還是不知道如何訪問它的成分標題
如果我不使用重定向,我將如何把它傳遞給另一個
class Header extends React.Component { render() { return ( <header> <nav> <p className="menuButton"><Link to='/'>Home</Link></p> <p className="menuButton"><Link to='/login'>Login</Link></p> </nav> </header> ) } }
登錄組件:?
class Login extends React.Component {
constructor(props) {
super(props)
this.state = {
username:'',
email: '',
password: ''
}
this.loginFunc = this.loginFunc.bind(this)
}
loginFunc(){
... getting user data ...
this.setState({
username:response.firstname
})
...
history.push('/', { username: response.firstname });
history.go('/');
}
}
這是不可能的。爲了獲得數據登錄,你也必須在頁面上顯示頁眉。除非你使用像flux,redux這樣的東西有一個很大的可共享狀態。 – Nicholas
你應該使用像redux,flux這樣的狀態管理器。 –