创建 store
redux/index.js
import { createStore } from 'redux';
const defaultState = {
language: 'zh',
languageList: [
{ name: '中文', code: 'zh' },
{ name: '英文', code: 'en' }
]
}
const reducer = (state = defaultState, action) => {
switch (action.type) {
case "change_labguage":
return { ...state, language: action.payload };
default:
return state
}
}
const store = createStore(reducer);
export default store;
在类组件中使用
import React from 'react';
import store from 'redux/index'
// 在 类中使用 redux
class HeaderComponet extends React.Component {
constructor(props) {
super(props);
// 获取 store 数据参数
const storeState = store.getState();
this.state = {
language: storeState.language,
languageList: storeState.languageList
}
// 订阅 store
store.subscribe(() => {
// 重新取出新数据
const newState = store.getState();
this.setState({
language: newState.language,
languageList: newState.languageList
})
});
}
menuClickHander = (e) => {
const action = {
type: 'change_labguage',
payload: e.key
}
// 向仓库去分发指令
store.dispatch(action);
}
render() {
return (
<div className="header">
<Dropdown.Button
overlay={
<Menu onClick={() => this.menuClickHander} items={this.state.languageList.map(l => {return {key: l.code, label: l.name} })}/>
}>{ this.state.language === 'zh' ? '中文': 'English' }</Dropdown.Button>
</div>
)
}
}
函数组件中使用
跟类组件使用类似,通过注入的方式使用