问题
I'm trying to create a simple component to dispatch an action using the React Redux hook useDispatch
- and I'm getting an error. I've trimmed the component down to where the error occurs. It happens when the useDispatch function is called.
import { useDispatch } from 'react-redux'
const MyComp = () => {
useDispatch()
return null
}
export default MyComp
This is the error I'm seeing in dev console:
Uncaught TypeError: Object(...) is not a function
at MyComp (MyComp.js?cc4c:4)
at renderWithHooks (react-dom.development.js?d018:12938)
at mountIndeterminateComponent (react-dom.development.js?d018:15020)
at beginWork (react-dom.development.js?d018:15625)
at performUnitOfWork (react-dom.development.js?d018:19312)
at workLoop (react-dom.development.js?d018:19352)
at HTMLUnknownElement.callCallback (react-dom.development.js?d018:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js?d018:199)
at invokeGuardedCallback (react-dom.development.js?d018:256)
at replayUnitOfWork (react-dom.development.js?d018:18578)
I've trimmed this down further so there are no parents in the react tree.
const store = configureStore()
ReactDOM.render(
<Provider store={store}>
<MyComp />
</Provider>,
document.getElementById('root')
)
Module Versions
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.1.0",
回答1:
In my case, I was doing:
import { useDispatch } from 'react'
instead of:
import { useDispatch } from 'react-redux'
🤦♂️
回答2:
I got it working - I think by just stopping, building, restarting the app. I didn't expect useDispatch
to need this, so I can't explain why that would have helped.
A note - I did try useSelector
and that did work, I could output the useSelector variable to console after import from react-redux (console.log of useDispatch was undefined). I could tell at that point I was on the right version of React, and this was probably a problem of my system.
So, if you are having a similar issue. Try a full react app restart. Confirm you are loading the correct version of react.
回答3:
I'm using @reduxjs/toolkit
, and assumed react-redux
was already installed.
回答4:
I had a similar issue, and the fix was to update "react-redux". Initial package.json was like this:
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^6.0.1",
The problem disappeared after installing react-redux@7.2.0
回答5:
upgrading from
"react-redux": "6.0.1",
to
"react-redux": "7.2.0",
fixed it for me
run npm outdated
for an overview, and then npm update react-redux
to update redux
来源:https://stackoverflow.com/questions/57277698/react-redux-usedispatch-uncaught-typeerror