简体   繁体   English

组件未重新渲染时如何获取更新的 redux-toolkit state

[英]How to get updated redux-toolkit state when component is not re-render

I'm trying to delete item in redux toolkit, but don't know how, the remove function only work on screen, i have to press twice to delete the previous one我正在尝试删除 redux 工具包中的项目,但不知道如何,删除 function 只能在屏幕上工作,我必须按两次才能删除前一个

Here is the reducer这是减速机

const noteReducer = createSlice({
  name: "note",
  initialState: NoteList,
  reducers: {
    addNote: (state, action: PayloadAction<NoteI>) => {
      const newNote: NoteI = {
        id: new Date(),
        header: action.payload.header,
        note: action.payload.note,
        date: new Date(),
        selectStatus: false,
      };
      state.push(newNote);
    },
    removeNote: (state, action: PayloadAction<NoteI>) => { // 
 ======> Problem here
      return state.filter((item) => item.id !== action.payload.id);
    },
    toggleSelect: (state, action: PayloadAction<NoteI>) => {
      return state.map((item) => {
        if (item.id === action.payload.id) {
          return { ...item, selectStatus: !item.selectStatus };
        }
        return item;
      });
    },
    loadDefault: (state) => {
      return state.map((item) => {
        return { ...item, selectStatus: false };
      });
    },
    resetNote: (state) => {
      return (state = []);
    },

    editNote: (state, action: PayloadAction<NoteI>) => {
      return state.map((item) => {
        if (item.id === action.payload.id) {
          return {
            ...item,
            note: action.payload.note,
            header: action.payload.header,
            date: action.payload.date,
          };
        }
        return item;
      });
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchNote.fulfilled, (state, action) => {
      state = [];
      return state.concat(action.payload);
     
    });
    
  },
});

Here is the function where i use it: CODE UPDATED这是我使用它的 function:代码已更新

export default function NoteList(props: noteListI) {
  const { title, note, id, date } = props;
  const data = useSelector((state: RootState) => state.persistedReducer.note);
   useEffect(() => {
    currentDate.current = data;
  }, [data]);
  const removeSelectedNote = () => {
    dispatch(removeNote({ id: id }));
    console.log(data);  ====> still log 4 if i have 4
  };
 console.log(data); // ====> work if i log here but a lots of logs

  return (
    <View>
      <TouchableOpacity
        onLongPress={() => {
          removeSelectedNote();
          console.log("current", currentDate.current);   ///same
        }}
        // flex
        style={CONTAINER}
        onPress={() =>
          !toggleSelectedButton ? onNavDetail() : setEnableToggle()
        }
      >
        <Note
          note={note}
          header={title}
          date={date}
          id={id}
          selectedStatus={selectedButtonStatus}
        />
      </TouchableOpacity>
    </View>
  );
}

I have to press twice to make it work, for example, i have 4 item, when i press one, the item on screen disappears but the data log still have 4 item, when i click another, it show 3 on console.log but the screen display 2, the redux state is change outside the return() but i can't capture the updated state, it work the previous one我必须按两次才能使其工作,例如,我有 4 个项目,当我按一个时,屏幕上的项目消失但数据日志仍然有 4 个项目,当我单击另一个时,它在 console.log 上显示 3 但是屏幕显示 2,redux state 在return()之外发生了变化,但我无法捕获更新后的 state,它适用于前一个

Here is a gif to show what going on这是一个 gif 来显示发生了什么

在此处输入图像描述

When i press only one item, it change on UI but when i refresh it return same state当我只按一项时,它会在 UI 上发生变化,但是当我刷新它时返回相同的 state

在此处输入图像描述

When i click twice or more, it make changes to previous当我单击两次或更多时,它会更改以前的在此处输入图像描述

Updated更新

The redux-persist code: redux-persist 代码:

const reducer = combineReducers({
  note: noteReducer,
  firebase: authentication,
});
const persistConfig = {
  key: "root",
  storage: AsyncStorage,
  blacklist: [],
};

const persistedReducer = persistReducer(persistConfig, reducer);
const store = configureStore({
  reducer: { persistedReducer, toggle: toggleReducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

export default store;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const persistStorageNote = persistStore(store);

I also added the useEffect by this, but problem is when i log the changes in function, it remain the same:我还通过这个添加了useEffect,但问题是当我记录function中的更改时,它保持不变:

在此处输入图像描述

here is how you can log updated data correctly, as state update is asynchronous it doesn't change immediately when you dispatch removeNote这是正确记录更新数据的方法,因为 state 更新是异步的,它不会在您发送removeNote时立即更改

export default function NoteList(props: noteListI) {
  const { title, note, id, date } = props;
  const data = useSelector((state: RootState) => state.persistedReducer.note);
  // log changed data
   useEffect(() => {
     console.log(data); 
  }, [data]);
  const removeSelectedNote = () => {
    dispatch(removeNote({ id: id }));
  };
 

  return (
    <View>
      <TouchableOpacity
        onLongPress={() => {
          removeSelectedNote();
        }}
        // flex
        style={CONTAINER}
        onPress={() =>
          !toggleSelectedButton ? onNavDetail() : setEnableToggle()
        }
      >
        <Note
          note={note}
          header={title}
          date={date}
          id={id}
          selectedStatus={selectedButtonStatus}
        />
      </TouchableOpacity>
    </View>
  );
}

about reloading issue, try to close the app and open it like a user of your app would ( minimize the app -> remove the app from recently opened apps -> open app again ), instead of reloading the project.关于重新加载问题,尝试关闭应用程序并像您的应用程序用户那样打开它( minimize the app -> remove the app from recently opened apps -> open app again ),而不是重新加载项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尽管Redux状态已更新,但组件未重新渲染 - Component does not re-render although redux state is updated 使用 react、redux 和 immer 更新状态时,组件不会重新渲染 - Component does not re-render when State is updated using react, redux and immer <Redux>状态更新但不重新渲染 - <Redux> state updated but nor re-render 更新 state 时反应 @redux/toolkit 不重新渲染组件 - React @redux/toolkit not re-rendering component when state is updated 更新来自redux的道具后,react组件应如何重新呈现自身? - How should the react component re-render itself when props from redux have been updated? Redux-Toolkit 和 React Hooks - Store 更改不会触发重新渲染 - Redux-Toolkit and React Hooks - Store change does not trigger re-render React / Redux:状态在Redux对象中更新,但是React组件不会重新渲染 - React/Redux: State is updated in Redux object, but React component doesn't re-render 从 Redux state 映射数组时,如何仅重新渲染新的子组件? - How can i only re-render the new child component when mapping an array from Redux state? 当 state 更新时,组件不会使用更新的 state 重新渲染(反应) - When state is updated, component does not re-render with updated state (REACT) Function 未收到更新的 redux state 即使重新渲染 - Function not receiving updated redux state even on re-render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM