安裝 redux react-redux redux-thunk
yarn add redux react-redux redux-thunk
項目目錄如下
項目中添加store/actions/index.js
const login = user => {
return {
type: 'LOGIN',
user,
};
};
添加store/reducers/index.js
import {combineReducers} from 'redux';
const login = (state = {}, action) => {
switch (action.type) {
case 'LOGIN':
return {
...action.user,
};
break;
default:
return state;
}
}
export default combineReducers({
login
});
編寫store/index.js
//store/index.js
import {createStore, applyMiddleware, compose} from 'redux';
//引入Reducer
import Reducer from './reducers';
//引入中間件
import thunkMiddleware from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
const configureStore = (initialState) => {
const store = createStoreWithMiddleware(Reducer, initialState);
return store;
}
export default configureStore()
修改index.js
//...
import {ConfigProvider} from 'antd';
import {Provider} from 'react-redux';
import store from './store'
ReactDOM.render(<ConfigProvider locale={zh_CN}>
<Provider store={store}>
<Router/>
</Provider>
</ConfigProvider>, document.getElementById('root'));
serviceWorker.unregister();
修改業(yè)務組件 以app.js為例
import React, {Component} from 'react';
import {connect} from 'react-redux';
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (<div>appIndexPage</div>)
}
}
//添加store中的state
const mapStateToProps = (store) => {
return store;
};
//添加dispatch方法
const mapDispatchToProps = (dispatch) => {
return {
dispatch
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
驗證
到其他業(yè)務組件里面驗證
結束
本文章主要提供展示--請根據自身情況合理優(yōu)化項目哟旗、代碼某宪、以及更多功能