react-redux 官网地址:https://react-redux.js.org/
安装react-redux
npm install react-redux
在index.tsx文件中,引入react-redux
import store from './redux/store';
import {Provider} from 'react-redux';
ReactDOM.render(
<React.StrictMode>
<Provider store={store} >
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
在header.tsx中使用connect进行props注入
import { connect} from 'react-redux';
import { Dispatch } from "redux";
import {RootState} from '../../redux/store';
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 HeaderComponent extends React.Component<PropsType>{
menuClickHander = (e)=>{
if(e.key === 'new'){
//使用props
this.props.addLanguage('新语言', 'new_lang')
}else{
this.props.changeLanguage(e.key);
}
}
render(){
return <Menu onClick={this.menuClickHander}>
{this.props.languageList.map(l => <Menu.Item key={l.code}>
{l.name}</Menu.Item>)}
<Menu.Item key={'new'}>{t('header.add_new_language')}</Menu.Item>
</Menu>
}
}
export const Header = connect(mapStateToProps,mapDispatchToProps)(withTranslation()(withRouter(HeaderComponent)));