在之前的 React-Redux-优化 文章当中说明了一个问题需要解决,在本文主要介绍的就是这个问题的解决方案;
- store、action、reducer 代码都写在一个文件中,不利于维护
这个问题呢,可以在项目工程当中新建一个 store 文件夹,在该文件夹当中分别创建 action.js
,constants.js
,reducer.js
,store.js
等文件:
- action.js
import {
ADD_COUNT,
SUB_COUNT
} from './constants';
// 利用action来修改状态
export const addAction = (num) => {
return {type: ADD_COUNT, num: num};
};
export const subAction = (num) => {
return {type: SUB_COUNT, num: num};
};
- constants.js
export const ADD_COUNT = 'ADD_COUNT';
export const SUB_COUNT = 'SUB_COUNT';
- reducer.js
import {
ADD_COUNT,
SUB_COUNT
} from './constants';
// 定义一个状态
let initialState = {
count: 666
};
// 利用reducer将store和action串联起来
function reducer(state = initialState, action) {
switch (action.type) {
case ADD_COUNT:
return {count: state.count + action.num};
case SUB_COUNT:
return {count: state.count - action.num};
default:
return state;
}
}
export default reducer;
- store.js
import {createStore} from 'redux';
import reducer from './reducer';
// 利用store来保存状态(state)
const store = createStore(reducer);
export default store;
使用 Redux
- App.js
import React from 'react';
import store from './store/store';
import {addAction, subAction} from './store/action';
class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: store.getState().count
}
}
componentDidMount() {
store.subscribe(() => {
this.setState({
count: store.getState().count
})
})
}
componentWillUnmount() {
store.unsubscribe();
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => {
this.btnClick()
}}>
增加
</button>
</div>
)
}
btnClick() {
store.dispatch(addAction(5));
}
}
export default App;