javascript 使用Redux和Redux Toolkit更新React原生待办事项应用中的待办事项列表

rn0zuynd  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(145)

我正在构建一个RN Todo应用程序,它有2个屏幕,分别命名为主屏幕和编辑屏幕,看起来像HomeScreenEditScreen
但是我不知道如何使用Redux从EditScreen更新。请给予我一些解决方案。我真的很感激。
如果您需要更多的详细信息来帮助我解决此问题,请告诉我。
store.js

const reducers = combineReducers({
  tasks: taskSlice,
});
const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['tasks'],
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
  reducer: persistedReducer,
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk]
});

taskSlice.js

export const taskSlice = createSlice({
  name: 'tasks',
  initialState: [],
  reducers: {
    addTask: (state, action) => {
      console.log(nanoid());
      // 'dgPXxUz_6fWIQBD8XmiSy'

      console.log(action.payload);
      const newTask = {
        id: nanoid(),
        name: action.payload.task,
      };
      state.push(newTask);
    },
    deleteTask: (state, action) => {
      console.log('delete', action.payload.id);
      console.log('state', state);
      return state.filter(item => item.id !== action.payload.id);
    },
    editTask: ???
  },
});

EditScreen.js

<TouchableOpacity
  style={styles.button}
  onPress={() => {
    // ???
  }}>
  <Text style={{color: 'white'}}>Update</Text>
</TouchableOpacity>
hjqgdpho

hjqgdpho1#

你需要改变一点点在你的redux设置有一个看看下面

const taskSlice = createSlice({
  name: 'tasks',
  initialState: [],
  reducers: {
    addTask: (state, action) => {
      console.log(nanoid());
      // 'dgPXxUz_6fWIQBD8XmiSy'

      console.log(action.payload);
      const newTask = {
        id: nanoid(),
        name: action.payload.task,
      };
      state.push(newTask);
    },
    deleteTask: (state, action) => {
      console.log('delete', action.payload.id);
      console.log('state', state);
      return state.filter(item => item.id !== action.payload.id);
    },
    editTask: (state, action) => {
      const index = state.findIndex(item => item.id === action.payload.id);
      const updatedState = [...state];
      updatedState[index].name = action.payload.name;
    },
  },
});

export const {addTask, deleteTask,editTask} = taskSlice.actions;
export default taskSlice.reducer;

并从EditScreen.js通过发送已编辑的taskid和任务名称来更新任务

import {useDispatch} from 'react-redux';
import {editTask} from '....path of taskSlice.js';
...

const dispatch = useDispatch();

const update = () => {
  dispatch(editTask({id:'<taskid>',name:'<editted_task_name>'}));

<TouchableOpacity
  style={styles.button}
  onPress={update}>
  <Text style={{color: 'white'}}>Update</Text>
</TouchableOpacity>

相关问题