首页 > 解决方案 > 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>
);

标签: react-nativereduxreact-redux

解决方案


我认为您正在寻找的是redux-persist,因此每次创建商店时,它都会尝试使用异步存储来获取以前的数据,并且当您向商店添加内容时,它将被持久保存到异步存储中。

这是一个非常好的教程https://blog.reactnativecoach.com/the-definitive-guide-to-redux-persist-84738167975

注意:如果您的异步存储中还没有任何内容,则需要先添加待办事项


推荐阅读