Javascript 使用localstorage在React或React Native中仅显示一次组件
我遇到了以下情况,我试图使用localstorge只显示一次屏幕组件。这件事让我发疯 App.jsJavascript 使用localstorage在React或React Native中仅显示一次组件,javascript,reactjs,react-native,local-storage,asyncstorage,Javascript,Reactjs,React Native,Local Storage,Asyncstorage,我遇到了以下情况,我试图使用localstorge只显示一次屏幕组件。这件事让我发疯 App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } componentDidMount() { if (AsyncStorage.getItem('key')) { AsyncStorage.getItem('key', (val
...
constructor(props) {
super(props);
this.state = {
isLoading: false,
};
}
componentDidMount() {
if (AsyncStorage.getItem('key')) {
AsyncStorage.getItem('key', (value) => {
this.setState({isLoading: value})
Alert.alert(JSON.stringify(value))
});
AsyncStorage.setItem('key', JSON.stringify(true))
}
}
render() {
if (!this.state.isLoading) {
return <Search />
}
return <Root />
}
...
。。。
建造师(道具){
超级(道具);
此.state={
孤岛加载:false,
};
}
componentDidMount(){
if(AsyncStorage.getItem('key')){
AsyncStorage.getItem('键',(值)=>{
this.setState({isLoading:value})
Alert.Alert(JSON.stringify(value))
});
AsyncStorage.setItem('key',JSON.stringify(true))
}
}
render(){
如果(!this.state.isLoading){
返回
}
返回
}
...
您需要稍微修改componentDidMount
实现,并向组件的状态添加另一个标志
constructor() {
...
this.state = {
isLoaded: false,
wasShown: false
}
}
componentDidMount() {
AsyncStorage.getItem('key') // get key
.then(wasShown => {
if(wasShown === null) { // first time
// we need to save key for the next time
AsyncStorage.setItem('key', '"true"')
}
this.setState({isLoaded: true, wasShown})
})
}
render() {
const { isLoaded, wasShown } = this.state
// you can't tell if this component was shown or not render nothing
if(!isLoaded) { return null }
if(!wasShown) {
return <Search />
}
return <Root/>
}
在检查存储值时显示其他内容。在获得值后,只需设置状态并显示屏幕。换句话说,只有在确定尚未显示屏幕后,才应打开屏幕组件。AsyncStorage的异步性很好,如果(AsyncStorage.getItem('key'),则不能通过这种方式检查是否存在密钥{Ah,关于如何实现这一点的任何解决方法?使用redux persist可以实现这一逻辑吗?我可以使用redux设置值,但不确定如何处理在redux persistMB中获取密钥的存储方法。我从未使用过redux persist包。
AsyncStorage.getItem('isShown').then((value) => {
if(value == null){
// Whatever you want to do just once.
AsyncStorage.setItem('isShown', 'sth');
}
});
AsyncStorage.getItem('isShown').then((value) => {
if(value == null){
// Whatever you want to do just once.
AsyncStorage.setItem('isShown', 'sth');
}
});