redux学习-简单实例
react + redux 简单实例 // 通过redux 实现计数
redux devtools使用方法
1. 创建文件目录
2. 创建redux
- 2.1 创建store
// /src/redux/store/index.js
import { createStore } from 'redux';
import reducers from './../reducers';
const store = createStore(reducers);
export default store;
- 2.2 创建actionTypes
// /src/redux/action/index.js
export const actionTypes = {
ADD_TEST: 'ADD_TEST',
};
- 2.2 创建reducers
// /src/redux/reducers/index.js
import { actionTypes } from './../action';
const initialState = {
number: 11,
};
export default (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_TEST:
return {
...state,
number: action.number + 1
};
default:
return state;
}
}
此时一个完整的redux已经创建完成,接下来需要将redux与react相连接
3. react与redux连接
- 3.1 使用Provider包裹项目根目录
修改前
// 修改前
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<App />,
document.getElementById('root'));
registerServiceWorker();
修改后
// 修改后
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'; // 新增
import store from './redux/store'; // 新增
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Provider store={store}>// 新增
<App />
</Provider>,// 新增
document.getElementById('root'));
registerServiceWorker();
3.2 在项目中使用redux
3.2.1 通过dispatch修改store数据
通过dispatch触发store数据的改变
3.2.2 获取store中的数据
通过connect将export default App修改为 export default connect(mapStateToProps)(App); 即可通过this.props 获取到store中数据
import React, {Component} from 'react';
import {Button} from 'antd'; // 加载 JS
import { actionTypes} from './redux/action'; // 新增
import { connect } from 'react-redux'; // 新增
class App extends Component {
constructor(props) {
super(props);
this.handleBtnClick = this.handleBtnClick.bind(this);
}
handleBtnClick() {
const { dispatch } = this.props; // 新增
const action = {
type: actionTypes.ADD_TEST,
number: this.props.number
};
dispatch(action);
}
render() {
return (
<div>
<Button onClick={this.handleBtnClick}>自增</Button>
<p>{ this.props.number }</p>
</div>
)
}
}
// 新增
const mapStateToProps = (state) => {
return {
number: state.number
};
};
// 修改
export default connect(mapStateToProps)(App);
总结
step1:创建redux
- 创建store;
- 创建action;
- 创建reducers;
step: 连接react
- Provider包裹跟组件, 制定store={store};
- connect 连接业务组件,通过dispatch修改,mapStateToProps获取;