簡體   English   中英

React Redux 工具包隱藏顯示模式

[英]React Redux toollkit hide show modal

我是使用 redux 工具包的新手,想問我應該如何更新我的模式,在我的減速器中,我嘗試將 state.modal 更新為 action.payload,但它似乎不起作用。

export const uiSlice = createSlice({
  name: "ui",
  initialState: {
    modal: {
      type: "",
    },
  },
  reducers: {
    showModal: (state, action) => {
      state.modal.type === action.payload
    },
    hideModal: (state) => {
      state.initialState;
    },
  },
});

const handleOpenModal = () => {
    dispatch(showModal(TESTMODAL));
};

如果您只是試圖將模態切換為“顯示”和“隱藏”,則可以將模態設置為“布爾值”。 然后,您可以訪問減速器中的“initialState”並將其設置為與先前狀態相反的狀態(使用“!”)。

export uiSlice = createSlice({
  name: "ui",
  initialState: {
    showUi: false,
  },
  reducers: {
    toggleUiShow: (state) => {
      state.showUi = !state.showUi;
    },
  },
});

export const {toggleUiShow} = uiSlice.actions;
export default cartSlice.reducer;

在你創建了一個 store 並導出了你的 reducer 函數之后——你可以將 state、dispatch 函數以及 action 導入到所需的組件中。 要訪問狀態,您還需要導入 useSelector 掛鈎。

例如,在您的函數組件中:

import { useSelector } from 'react-redux';
//in your function component you can access the state with the useSelector hook

const showUI = useSelector((state)=>state.[your_pointer_from_store].showUi)

現在您已將狀態存儲在變量中,並且可以訪問所需組件主體中的狀態。 調度函數...

import { useDispatch } from 'react-redux';
import { toggleUiShow} from 'your-js-file'
//in your function component you can update the state with the useDispatch hook
//
const dispatch = useDispatch()
//
const toggleHandler = ()=>{
   dispatch(toggleUiShow()) 
}
//pass the handler to the required function ie. onClick={toggleHandler}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM