I know how to to dispatch and get store using functional component. There is a great documentation about it here
But what about class component? How to get store and fire dispatch using class component. There is nothing said about it.
Lets say I defined hooks.ts:
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { RootState, AppDispatch } from './store/store';
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
And I need this functional component make as class:
import {useAppDispatch, useAppSelector} from "../../../hooks"
import { setRelease } from "./../store/factorySlice/factorySlice"
const X: React.FC = () => {
const {selectedRelease} = useAppSelector(store => store.factory)
const dispatch = useAppDispatch()
return (
<>
{selectedRelease}
<button onClick={() => dispatch(setRelease())}>Click</button>
</>
)
}
CodePudding user response:
Redux Toolkit
is our official recommended approach for writing Redux logic. It wraps around theRedux
core, and contains packages and functions that we think are essential for building a Redux app
You can use it with class component by using react-redux
's connect
API:
import { connect } from "react-redux";
import { setRelease } from "./../store/factorySlice/factorySlice"
class X extends React.Component {
render() {
return (
<>
{this.props.selectedRelease}
<button onClick={() => this.props.dispatch(setRelease())}>Click</button>
</>
);
}
}
const mapStateToProps = (state) => ({
selectedRelease: state.factory.selectedRelease
});
export default connect(mapStateToProps)(X);
CodePudding user response:
This was the first implementation. You would connect the class component to the store like
connect()(MyComponent)
Where Class is MyComponent