react-native - Read the saved data initially in react native and redux
问题描述
I am learning redux. I am testing it in todo app. Everything works fine but how can I display the saved todos in the beginning. I've used AsyncStorage to store the todos list in reducer and tried to read them in mapstatetoProps function but in vain. How can I do that. Thankyou
store
import { createStore } from "redux";
import rootReducer from "../reducers";
export default (store = createStore(rootReducer));
reducer
let nextId = 0;
let newState = [];
saveTodos = newToDos => {
const saveTodos = AsyncStorage.setItem(
"savedToDoList",
JSON.stringify(newToDos)
);
};
const todos = (state = [], action) => {
switch (action.type) {
case "ADD_TODO":
newState = [
...state,
{
id: nextId++,
text: action.todo,
completed: false
}
];
this.saveTodos(newState);
return newState;
case "TOGGLE_TODO":
return state.map(
todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
);
default:
return state;
}
};
visibleTodo.js
const mapStateToProps = state => {
return {
todoss: state.todos
};
};
const mapDispatchToProps = dispatch => ({
toggleTodo: id => dispatch({ type: "TOGGLE_TODO", id })
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(ToDoList);
ToDoList.js
const ToDoList = ({ todoss, toggleTodo }) => (
<View style={{ padding: 20 }}>
{todoss.map(todo => (
<TouchableOpacity key={todo.id} onPress={() => toggleTodo(todo.id)}>
<Text
style={{
fontSize: 16,
color: "gray",
textDecorationLine: todo.completed ? "line-through" : "none"
}}
>
{todo.id + 1 + ". " + todo.text}
</Text>
</TouchableOpacity>
))}
</View>
);
解决方案
我认为您正在寻找的是redux-persist,因此每次创建商店时,它都会尝试使用异步存储来获取以前的数据,并且当您向商店添加内容时,它将被持久保存到异步存储中。
这是一个非常好的教程https://blog.reactnativecoach.com/the-definitive-guide-to-redux-persist-84738167975
注意:如果您的异步存储中还没有任何内容,则需要先添加待办事项
推荐阅读
- javascript - 使用 reducer 越多,store 中的 state 对象是否会不断增长?
- api - 从 Linkedin API 获取工作列表
- angular - default option not displaying in Angular 8 reactive form
- arduino - Why does division in #define cause division in code to output a different answer
- oracle - SQL%ROWCOUNT 返回 1,但没有更新任何行
- r - 如何在 R 中解决这个问题:在 while (t <= cc[i]) { ... : 条件的长度 > 1 并且只使用第一个元素
- python - 在 DataFrame 上使用 str.split(expand=True) 处理海量数据集
- group-by - Dplyr 汇总函数列表和对其他数据列的依赖
- ocaml - Flow Parser AST 上模式匹配的一般策略
- java - 尝试将 JpaRepository 注入 AWS Lambda 时没有合格的 bean