[英]ReactJs React-Router Navigation
我陷入了一些與react-router導航相關的問題。 在我的導航中,有2個菜單登錄和注冊,而我的索引頁是登錄。
在登錄頁面上輸入電子郵件和密碼的值並提交登錄按鈕后,它將輸出為sessionValue。我的sessionValue是從serverSide返回的用戶名,並重定向到TodoApp頁面。 登錄后,它重定向到TodoApp頁面。 我想顯示注銷菜單,而不是在導航中登錄。
我的代碼如下:
app.jsx
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Main}>
<Route path="RegistrationForm" component={RegistrationForm}/>
<Route path="todoapp/:sessionValue"component={TodoApp}/>
<IndexRoute component={Login}/>
</Route>
</Router>,
document.getElementById('app')
);
導航組件
我通過使用localstorage進行了嘗試,但是它不起作用。 僅當我單擊瀏覽器的后退箭頭時,它才起作用。
var Nav= React.createClass({
render:function(){
var strUserName = localStorage.getItem('sessionValue');
console.log(strUserName);
function loginMenu(){
if(strUserName){
return <Link to="/RegistrationForm" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Logout</Link>
}
else{
return <IndexLink to="/" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>LogIn</IndexLink>
}
}
return(
<div className="top-bar">
<div className="top-bar-left">
<ul className="menu">
<li className="menu-text">
React App
</li>
<li>
{loginMenu()}
</li>
<li>
<Link to="/RegistrationForm" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Signup</Link>
</li>
</ul>
</div>
</div>
);
}
});
module.exports=Nav;
登錄頁面(login.jsx)
if(validForm){
axios.post('/login', {
email:this.state.strEmail,
password:this.state.strPassword
})
.then(function (response) {
//console.log(response.data);
var sessionValue=response.data;
//After login todoApp page is open and with session value.session value passed through url to todoApp.
browserHistory.push(`todoapp/${sessionValue}`);
localStorage.setItem('sessionValue',sessionValue);
})
.catch(function (error) {
console.log(error);
});
}
},
問題:
您應該在后台有一些狀態管理策略來實現此行為。 因此,您可以具有以下組件結構
App
- Nav
- LoginForm
沒有任何狀態管理庫(例如redux / mobX),您需要在App組件中定義狀態
class App extends Component {
constructor(props) {
super(props);
this.onLoggedInChanged = this.onLoggedInChanged.bind(this);
this.state = {
isLoggedIn: false
}
}
onLoggedInChanged(isLoggedIn) {
this.setState({
isLoggedIn: isLoggedIn
});
}
render() {
return (
<Nav isLoggedIn={this.state.isLoggedIn} />
<LoginForm onLoggedInChanged={this.onLoggedInChanged}></LoginForm>
);
}
}
然后在Nav組件中,可以使用isLoggedIn
標志
Nav = () => {
let loginElement = this.props.isLoggedIn ? 'Logged in user' : 'Not logged in'
return (<div>{loginElement }</div>)
}
您可以在https://facebook.github.io/react-native/docs/state.html的文檔中找到有關React應用程序中狀態的更多信息。
在redux / mobx中,它將以另一種方式完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.