如何根据路由器端的条件分派操作
How to dispatch an action based on a condition in side a router
如何根据条件以正确的方式调度操作:
我执行了以下操作,但出现语法错误。
const PrivateRoute = ({ component: Component, ...rest }) => {
<Route {...rest} render={props => (
firebase.auth().onAuthStateChanged((user) => user
?(
store.dispatch(actions.login(user.uid));
<Component {...props}/>
)
:(
store.dispatch(actions.logout());
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)
)}/>
}
正则括号 ((..)
) 让您 return 一个值。这就是您的语法错误的原因。您应该执行如下操作。
const PrivateRoute = ({ component: Component, ...rest }) => {
// return the Route component
return <Route {...rest} render={props => {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
// run dispatch
store.dispatch(actions.login(user.uid));
// return component
return <Component {...props} />
} else {
// run dispatch
store.dispatch(actions.logout());
// return component
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
}
});
}} />
}
如何根据条件以正确的方式调度操作: 我执行了以下操作,但出现语法错误。
const PrivateRoute = ({ component: Component, ...rest }) => {
<Route {...rest} render={props => (
firebase.auth().onAuthStateChanged((user) => user
?(
store.dispatch(actions.login(user.uid));
<Component {...props}/>
)
:(
store.dispatch(actions.logout());
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)
)}/>
}
正则括号 ((..)
) 让您 return 一个值。这就是您的语法错误的原因。您应该执行如下操作。
const PrivateRoute = ({ component: Component, ...rest }) => {
// return the Route component
return <Route {...rest} render={props => {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
// run dispatch
store.dispatch(actions.login(user.uid));
// return component
return <Component {...props} />
} else {
// run dispatch
store.dispatch(actions.logout());
// return component
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
}
});
}} />
}