我正在 React Native 中进行概念验证。我的想法是使用 AsyncStorage 保留少量数据,但在关闭和打开应用程序后这些数据不会持续存在。如果我不关闭应用程序,数据仍然存在。
我将值保存在减速器中,这是我的代码:
const initialState = {
data: [],
fetching: false
};
const todoReducer = (state = initialState, action) => {
console.log('action', action);
console.log('state', state);
let copied = Object.assign({}, state);
switch (action.type){
case ADD_TODO:
copied.data.push({ready: false, text: action.payload});
break;
case CHECK_TODO:
copied.data[action.payload].ready = true;
break;
case REMOVE_TODO:
copied.data.splice(action.payload, 1);
break;
case GETTING_DATA:
copied.fetching = true;
break;
case SET_STORE:
console.log('action.payload', action.payload);
copied.data = action.payload;
copied.fetching = false;
break;
default:
break;
}
AsyncStorage.setItem(STORAGE_TODO_KEY, JSON.stringify(copied.data));
return copied;
};
我还有一个用于查找信息的按钮(不是在保存后立即)并且在文本格式的示例中,这是代码
<Content>
<Text>{this.state.value}</Text>
<Button rounded style={{width: '100%', marginTop: 10}}
onPress={async ()=> {
try {
const value = await AsyncStorage.getItem(STORAGE_TODO_KEY);
if (value !== null) {
// We have data!!
console.log(value);
this.setState({value})
}else{
console.log('No hay data :c');
this.setState({value: 'No hay data :c'})
}
} catch (error) {
// Error retrieving data
console.log('Error', error);
this.setState({value: error})
}
}}>
<Text style={{textAlign: 'center', width: '100%'}}>Mostar lo guardado</Text>
</Button>
{this.props.todos.fetching && <Text>Cargando Lista de quehaceres...</Text>}
{
this.props.todos.data.length > 0 ?
this.renderTodoList()
: null
}
</Content>
在执行应用程序、保存数据并按下按钮的那一刻显示信息,即正在从 AsyncStorage 中恢复,但是一旦应用程序关闭它就不会返回数据