I am new in react and trying to learn redux. I want to access the store inside a class, but it gives me an error the I cant use hook in class.
When I use this code in function (as I saw in a YouTube tutorial), it works without any problem. Here I access to counter in the store.
function App() { const counter = useSelector(state => state.counter); return <div>{counter}</div>; }
but when I want to do this in class, it gives me an error that I can't use hooks in class.
So how can I access to my store either useSelector or useDispatch in class component?
Redux is a library that allows a React app to create a global state object that can be used in any component across the app by consuming the state object.
If you want to retrieve multiple values from the store, you can: Call useSelector() multiple times, with each call returning a single field value. Use Reselect or a similar library to create a memoized selector that returns multiple values in one object, but only returns a new object when one of the values has changed.
No worries, you can still use the older connect Higher Order Component to inject your redux state and dispatchable actions into the props passed to the component.
As @Ying Zuo said, your method works only with Functional Components. To solve this problem:
Instead of this line:
const counter = useSelector(state => state.counter);
You define the counter state like this:
const mapStateToProps = state => ({ counter: state.counter });
Then for dispatching you should use it like this:
const mapDispatchToProps = () => ({ increment, decrement });
At the end you combine everything like this:
export default connect( mapStateToProps, mapDispatchToProps() )(App);
Don't forget to import increment
and decrement
from your action
and connect
from the react-redux
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With