问题
I am new in react and trying to learn redux. now 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 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 cant use hooks in class.
so how can i access to my store either useSelector or useDispatch in class component?
回答1:
useSelector and useDispatch are React Hooks, which only work in function components.
https://reactjs.org/docs/hooks-overview.html#but-what-is-a-hook
With React Hooks, most components can and should be written with function components. If you have to write a class-based component, you can use connect from react-redux.
https://blog.logrocket.com/react-redux-connect-when-and-how-to-use-it-f2a1edab2013/
回答2:
as @Ying Zuo said, your method works only with function components.
for solving this specific 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 = () => {
return {
increment, decrement
};
};
at the end you combine everything like this:
export default connect(
mapStateToProps,
mapDispatchToProps()
)(App);
and dont forget to import "{increment, decrement}" from your action and "connect" from react-redux module
for more information, good youtube video that explains it very well (in my opinion):
https://www.youtube.com/watch?v=9d020AQCtcU
来源:https://stackoverflow.com/questions/57135857/how-can-i-use-react-redux-useselector-in-class-component