redux的使用流程
在store文件夹下的index.js文件中
1.安装 yarn add redux
2.引入 import {createStore,applyMiddleWare} from 'redux'
3.创建store const store = createStore(reduce函数,增强store/reduce的属性[可选])
4.导出 export default store
-------------------------------------------------------------
在store文件中创建常量文件,constants.js
书写常量 export const ADD_NUMBER = 'ADD_NUMBER';
------------------------------------------------------
在store文件夹下创建reducers文件夹
文件
xxxreducer / yyyreducer / zzzreducer
文件内容为
const defaulState = {}
function xxxreducer(defaultState,action){
case ADD_NUMBER:
......
default:
return defaultState
}
export default xxxreducer
合并reducer的文件
index.js
首先导入合并 reducer 的函数
import {combineReducers} from "redux";
const reducers = combineReducers({
xxxreducer,
yyyreducer,
zzzreducer
})
导出合并好的reducers
export default reducer
----------------------------------------------------------
在store下创建actions文件夹
文件
xxxaction / yyyaction / zzzaction
创建一个个的action
export const myaction1 = () => {
return {}
}
严格上来说action应该是一个对象,但是可以 通过redux-thunk中间件起作用
然后action也可以 是一个函数
export const myaction2 = () =>{
}
action需要通过dispatch来进行派发 : dispatch(myaction1())
dispatch(myaction2)
---------------------------------------------------------
最后使用connect来连接reduce和ui容器组件
安装 yarn add react-redux
在首页index.js导入store和Provide
import {Provider} from "react-redux";
使用
<Provider store = {store}><App></App></Provide>
在其他文件就 可以使用connect函数进行连接
导入 import {connect} from "react-redux";
const mapStateToProps = state => {
return {
xxx: state.xxx,
}
}
const mapDispatchToProps dispatch = > {
// 这里是一个个的函数
fun1() {
dispatch(myaction1())
}
fun2() {
dispatch(myaction2)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Home);
希望对你有一点点帮助,谢谢!!继续加油