我想使用redux/toolkit
创建一个全局模态组件并全局管理它。当我单击下拉菜单时,我创建了我想要显示模态的消息,当我单击“确定”或“取消”按钮和背景时,我尝试关闭它。
打开模态的事件没有问题,但要关闭它,请发送以下错误。附件是根据错误信息检查的内容。
的数据
- pacakge.json:
"react": "^18.2.0",
"react-copy-to-clipboard": "^5.1.0",
"react-dom": "^18.2.0",
字符串
- modalSlice.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
modalContent: '',
isOpen: false,
}
export const modalSlice = createSlice({
name: 'modal',
initialState,
reducers: {
openModal: (state, actions) => {
const { modalContent } = actions.payload
const updateState = {
...state,
isOpen: true,
modalContent,
}
return updateState
},
closeModal: (state, actions) => {
console.log(actions)
const updateState = {
...initialState,
}
return updateState
},
},
})
export const { openModal, closeModal } = modalSlice.actions
export default modalSlice.reducer
型
Modal.js
const Modal = () => {
const dispatch = useDispatch
const { modalContent } = useSelector((state) => state.modal)
const modalHandler = (e) => {
dispatch(closeModal)
}
return (
<>
<ModalContainer>
<ModalBack onClick={modalHandler} />
<ModalContentWrapper>
<ModalContent>{modalContent}</ModalContent>
<ModalBtnWrapper>
<ModalBtn onClick={modalHandler}>취소</ModalBtn>
<ModalBtn onClick={modalHandler}>확인</ModalBtn>
</ModalBtnWrapper>
</ModalContentWrapper>
</ModalContainer>
</>
)
}
型
- npm ls react
wedding_reception@0.1.0 /Users/mary/231014 wedding/mobile/wedding_reception
├─┬ @fortawesome/react-fontawesome@0.2.0
│ └── react@18.2.0 deduped
├─┬ @reduxjs/toolkit@1.9.5
│ └── react@18.2.0 deduped
├─┬ @testing-library/react@13.4.0
│ └── react@18.2.0 deduped
├─┬ react-copy-to-clipboard@5.1.0
│ └── react@18.2.0 deduped
├─┬ react-dom@18.2.0
│ └── react@18.2.0 deduped
├─┬ react-redux@8.1.1
│ ├── react@18.2.0 deduped
│ └─┬ use-sync-external-store@1.2.0
│ └── react@18.2.0 deduped
├─┬ react-router-dom@6.14.1
│ ├─┬ react-router@6.14.1
│ │ └── react@18.2.0 deduped
│ └── react@18.2.0 deduped
├─┬ react-scripts@5.0.1
│ └── react@18.2.0 deduped
├── react@18.2.0
└─┬ styled-components@6.0.2
└── react@18.2.0 deduped
型
2条答案
按热度按时间jecbmhm31#
无效的钩子调用警告您可能违反了钩子规则。
字符串
zphenhs42#
问题
起初,not 调用
useDispatch
会导致“invalid hook call”错误,这似乎很奇怪。在代码中,您保存了对useDispatch
钩子函数的引用并将其命名为dispatch
,然后在嵌套的回调函数中调用此函数,这显然违反了Rules of Hooks。只调用顶层钩子
不要在循环、条件或 * 嵌套函数 * 中调用Hooks。相反,在任何早期返回之前,始终在React函数的顶层使用Hooks。
字符串
溶液
在顶层正确调用
useDispatch
函数,以便 * 实际 *dispatch
函数在回调函数中可调用。型