使用redux及中间件thunk和devtools
安装
1.安装redux、react-redux、redux-thunk
npm install --save redux react-redux redux-thunk
2.安装辅助工具redux-devtools
npm install --save-dev redux-devtools-extension
使用
1.在store文件中引入
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension'
2.创建store并使用两个中间件
export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)))
将redux分为action、reducer、store三个部分
三部分介绍
store:redux的主体,一般创建之后不需要改动
reducer:用于编写更改store中数据的操作
action:将得到的数据进行处理(ajax等)后,触发reducer
action-type:用于统一action对象中type与reducer中的命名
store
如上面代码所示
// 引入reducer
import reducers from 'reducers'
// 创建store并抛出
export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)))
其中,reducer即为reducer.js文件返回的处理函数
reducer
如果action的type少的话可以写进一个函数,但当type多的时候,就应该将type分类
1.引入支持将type分类的方法
`import {combineReducers} from “redux”;
2.初始化出一个state
const initState = {
a: '',
b: ''
}
3.编写一个reducer函数
function ab(state=initState, action) {
switch (action.type) {
case changeA:
// 对action中的data进行处理
// JSON操作是深度拷贝,无特殊含义
let newState = JSON.parse(JSON.stringfy(state))
newState.a = action.data
// 返回新的state
return newState
default:
return state
}
}
4.将reducer使用combineReducers合并后抛出
export default combineReducers({
ab
})
action
当使用redux-thunk时,action不仅可以是一个对象,也可以是一个函数
export const changeA = (a) => {
// 前方可以做ajax请求等操作
return dispatch => {
dispatch({
type: changeA,
data: a
})
}
}
action_type
将上述所有用到action.type的值中统一替换为变量
抛出变量
export const CHANGE_A = 'changeA'
引入变量
import {CHANGE_A} from 'action_type'
在组件中使用
1.修改index.js使需要用到redux的组件被Provider包裹
引入Provider
import {Provider} from 'react-redux'
引入store
import store from "./redux/store";
修改render
ReactDOM.render(
<Provider store={store}>
// 组件
</Provider>,
document.getElementById('root')
);
2.在组件中使用
组件连接redux
引入connect
import {connect} from react-redux;
使用connect
export default connect(
state => ({}), // 当store中数据改变时的回调函数,相当于subscribe
{changeA} // 从action引入的函数
)(Register); // 填入组件类
对redux中数据进行改查操作
查询操作
this.props.a
修改操作(触发action)
引入对应action
import {changeA} from 'action';
在connect中,绑定action事件函数到props上
export default connect(
state => ({}), // 当store中数据改变时的回调函数,相当于subscribe
{changeA} // ***从action引入的函数***
)(Register); // 填入组件类
触发action事件函数
this.props.changeA('success')