First of all, I suggest you re-read the React.JS documentation, because there are a few things to note:
- Do not touch
this.statedirectly, use the method setState.(line: 108, 111, 121, 133, 136, 146) - , , .
(line: 111, 121, 136, 146)
; ;
:
1. Ajax , .
, ajax! , :
Ajax . JS console.log , , ajax-. :
$.ajax({ ...,
success: function(res) {
if(res) { self.setState({ auth : true }); }/
...
}
});
console.log(this.state.auth);
-, . , , this.state.auth false:
this.setState({ auth: true});
console.log(this.state.auth); // will print false, instead of true as your new value
componentWillUpdate(nextProps, nextState). : React.JS
2. componentWillReceiveProps() Navbar, this.props.auth undefined.
, setState() ajax. Navbar, , App ( auth), componentWillReceiveProps().
, :
const App = React.createClass({
getInitialState : function(){
return {
auth : false
}
},
componentDidMount : function() {
console.log('App componentDidMount');
this.checkAuth();
},
componentWillUpdate : function(nextProps, nextState) {
console.log('Your prev auth state: ' + this.state.auth);
console.log('Your next auth state: ' + nextState.auth);
},
checkAuth : function(){
var self = this;
$.ajax({
type : 'GET',
url : '/auth',
success : function(res){
if(res){
self.setState({ auth : true });
}
}
});
},
render : function(){
return(
<div className="appWrapper">
<Navbar auth={this.state.auth}/>
<div className="container">
{this.props.children}
</div>
</div>
);
}
});
// Navbar
// Because the navbar component receive data (this.props.auth) from parent (app) via props, so we're no longer need to assign auth as a state in Navbar component.
const Navbar = React.createClass({
render : function(){
// you're no longer need checkAuthState method
let navItems;
if(!this.props.auth){
navItems = (<ul className="nav navbar-nav navbar-right">
<li><a href="/login">Login</a></li>
<li><a href="/register">Register</a></li>
</ul>);
} else {
navItems = (<ul className="nav navbar-nav navbar-right">
<li><a href="/logout">Logout</a></li>
</ul>);
}
return (
<nav className="navbar navbar-default">
<div className="container">
<a href="/" className="navbar-brand">Reactor</a>
{ navItems }
</div>
</nav>
);
}
});
, !