Getting Started with React Redux | React Redux
1.安装
# If you use npm:
npm install react-redux
# Or if you use Yarn:
yarn add react-redux
cnpm i @types/react-redux -D
2.引用 index.tsx
import { Provider } from "react-redux";
import store from "./redux/store";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
3. connect
// HOC
import { connect } from "react-redux";
import { RootState } from "../../redux/store";
import { Dispatch } from "redux";
const mapStateToProps = (state: RootState) => {
return {
language: state.language,
languageList: state.languageList
}
}
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
changeLanguage: (code: "zh" | "en") => {
const action = changeLanguageActionCreator(code);
dispatch(action);
},
addLanguage: (name: string, code: string) => {
const action = addLanguageActionCreator(name, code);
dispatch(action);
},
};
};
type PropsType = RouteComponentProps & // react-router 路由props类型
WithTranslation & // i18n props类型
ReturnType<typeof mapStateToProps> & // redux store 映射类型
ReturnType<typeof mapDispatchToProps>; // redux dispatch 映射类型
class HeaderComponnet extends React.Component<PropsType> {
this.props.XXXXX
}
export const Header = connect(mapStateToProps, mapDispatchToProps)(
withTranslation()(withRouter(HeaderComponnet))
);