Хари Кришна!
Пишу приватный роутинг, использую react-route4.Работает на половину, скрывает компонент, но не показывает login form.
Я не совсем понимаю как передать из store значение моего auth в PrivateRoute компонент?
часть кода action/reducer login
const AUTH = 'AUTH';
export const auth = isAuth => ({
type: AUTH,
isAuth
});
//actions with auth
export function authenticated (username,password){
return dispatch => {
dispatch(auth(false));
sendRequestAuth(username, password)
.then(success =>{
dispatch(auth(true));
})
.catch(err=>{
dispatch(auth(false));
});
}
}
function sendRequestAuth (username,password) {
return new Promise ((resolve, reject) => {
setTimeout(()=>{
if (username === "admin" && password === "admin"){
return resolve(true)
} else {
return reject(new Error('Sorry, you are not admin ' ))
}
},1000);
});
}
export default function loginReducer (state = {
isAuth: false,
}, action){
switch (action.type){
case AUTH:
return {
...state,
isAuth: action.isAuth
};
}
часть кода компонента Login
lass Login extends Component {
constructor(props) {
super(props);
this.state = {
username:'',
password:'',
redirectToReferrer: false
};
this.onSubmit = this.onSubmit.bind(this);
};
onSubmit =(e) =>{
e.preventDefault();
let { username, password }=this.state;
this.props.login(username,password);
this.props.authenticated(username,password);
this.setState({
username: '',
password: '',
});
<i> if( this.props.authenticated === true){
this.setState({
redirectToReferrer: true</i>
});
}
};
render(){
const { from } = this.props.location.state || { from: { pathname: "/" }};
const { username, password,redirectToReferrer } = this.state;
if(redirectToReferrer){
return <Redirect to={from}/>
}
return (
<div className="form-login" >
<form name ="loginForm" onSubmit={this.onSubmit}>
</form>
</div>
)}
}
const mapStateToProps = (state)=>{
return { isAuth: state.isAuth};};
const mapDispatchToProps = (dispatch) => {
return {
login: (username, password) => dispatch(login(username,password)),
authenticated: (username, password) => dispatch(authenticated(username,password))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);
часть кода PrivateRoute
const PrivateRoute = ({ component: Component, ...rest })=>(
<Route {...rest} render={(props) => (
??????????????????????????????????????????????///
? <Component {...props} />
: <Redirect to='/login' />
)}
/>
);
const mapStateToProps = (state)=>{
return {
isAuth: state.isAuth
};
};
const mapDispatchToProps = (dispatch) => {
return {
authenticated: (username, password) => dispatch(authenticated(username,password))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute) ;