1.创建store
src/redux/store/index.js
import { createStore } from 'redux';
import reducers from '../reducers';
const store = createStore(reducers);
export default store;
2.创建actionTypes
src/redux/action/index.js
export const actionTypes = {
ADD_TEST: 'ADD_TEST',
};
3.创建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相连接
4.使用Provider包裹项目根目录
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
5.在项目中使用redux
App.js
import React, {Component} from 'react';
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);//通过dispatch修改store数据
}
render() {
return (
<div>
<button onClick={this.handleBtnClick}>自增</button>
<p>{ this.props.number }</p> //获取store中的数据
</div>
)
}
}
const mapStateToProps = (state) => {
return {
number: state.number
};
};
export default connect(mapStateToProps)(App);
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]) 连接 React 组件与 Redux store。
连接操作不会改变原来的组件类。反而返回一个新的已与 Redux store 连接的组件类。
[mapStateToProps(state, [ownProps]): stateProps
] (Function): 如果定义该参数,组件将会监听 Redux store 的变化。任何时候,只要 Redux store 发生改变,mapStateToProps
函数就会被调用。该回调函数必须返回一个纯对象,这个对象会与组件的 props 合并。如果你省略了这个参数,你的组件将不会监听 Redux store。如果指定了该回调函数中的第二个参数 ownProps
,则该参数的值为传递到组件的 props,而且只要组件接收到新的 props,mapStateToProps
也会被调用(例如,当 props 接收到来自父组件一个小小的改动,那么你所使用的 ownProps 参数,mapStateToProps 都会被重新计算)。