【问题标题】:How to make redirect after cleaning localstorage?清理本地存储后如何进行重定向?
【发布时间】:2020-06-13 08:24:07
【问题描述】:
清理本地存储后如何重定向到所需页面?
现在出现一个问题,用户按下按钮--Exit,localalStorage被清空,但是重定向没有发生。
const onHandleSignOut = () => {
localStorage.removeItem('session');
return <Redirect to="/auth" />
}
<li className="header__mainmenu-item" onClick={() => onHandleSignOut()}>
<FaSignOutAlt />
</li>
【问题讨论】:
标签:
reactjs
react-router-dom
【解决方案1】:
this.props.history.push("/auth");
希望对你有所帮助...
【解决方案2】:
您可以直接使用 window.location.href = '/ulr_to_redirect'; 进行重定向
【解决方案3】:
你可以创建一个组件在清理存储后进行重定向:
import { NavigationEvents } from 'react-navigation';
class Logout extends Component {
_clearAsyncStorage = async () => {
AsyncStorage.clear();
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Logout</Text>
<NavigationEvents onDidFocus={() => navigate('Login')} />
</View>
);
}
}
确保您已经在导航组件中创建了导航:
您可以使用 react navigation v4 或 v5 创建堆栈导航:
对我来说,在抽屉内添加了注销链接:
const AppDrawerNavigator = createDrawerNavigator(
.... other components
Déconnexion: {
screen: Logout,
navigationOptions: {
drawerIcon: ({ tintColor }) => (
<Icon
name={Platform.OS === 'ios' ? 'ios-exit' : 'md-exit'}
size={30}
style={styles(tintColor).drawerIcons}
type="material"
/>
),
},
)