-
react的数据是单项数据流,父子组件之间的通信, 通过props来传递数据。此时就出现一个问题,非父子组件之间的传参就比较复杂。Redux的出现就会很好的解决这一问题,Redux把数据全部存放在一个名为Store中,组件从Store中读取数据,在Store中对数据进行修改,就大大减少了组件之间数据的流通的过程,组件只需要从Store中读取数据即可。
-
Store: Redux中的Store是用来存储数据的,一个项目只能有一个Store。Redux提供的createStore 方法生成Store。
-
Action: Redux 提供一个对象来告知Store来进行修改state,这个对象就是Action,Action的type属性是必须的,其他属性根据需求添加。组件发出Action的唯一方法是store.dispatch(),store.dispatch()接受一个Action为参数,将它发送给Store告知Store修改相应的State。
-
Reducer: reducer是一个纯函数,Store接受Action然后修改State的的一个过程叫做reducer。
-
如何在项目中使用Redux。
-
首先初始化一个项目,安装相应依赖,安装react-redux。在跟目录创建一个store文件夹,下面创建文件如图
reducer文件中引入项目各个页面自己的reducer,然后通过combineReducers中间件合并不同页面的reducer。
index.js文件通过createStore生成根目录的Store。
`import { createStore, applyMiddleware } from ‘redux’;import reducer from ‘./reducer.js’
import thunk from ‘redux-thunk’;
const middleware = [thunk];
const store = createStore(reducer, applyMiddleware(…middleware));
export default store;`
-
在入口文件的index.js /ts中引入 Provider from react-redux. Provider 组件需要包裹在跟元素外面,它的作用是把store引入项目,并且之后的任意自组件,均可以获取store。
-
在页面中使用Redux,每个页面都有自己的Store文件,有各自的reducer,在页面中需要把store中的state与页面关联,需要借助connect。connect(mapStateToProps,mapDispatchToProps)(页面/组件); mapStateToProps是一个函数,是组件与store的state的映射关系,作为一个函数她接受两个参数,(state,props), state是store中的state,props是页面组件的props,第二个参数可以不传。它会返回一个对象object,传入state之后,如果store中的state发生改变,就会调用此函数,同步更新值,如果不传递props ,则不会同步监听。
`const mapStateToProps = (state)=>{return {
CategoryvalidateError:state.get(‘product’).get(‘CategoryvalidateError’),
Categoryhelp:state.get(‘product’).get(‘Categoryhelp’),
name:state.get(‘product’).get(‘editName’),
dec:state.get(‘product’).get(‘editDec’)
}
}mapDispatchToProps是用来建立组件和store.dispatch()之间的映射关系,可以是一个函数,当他为一个函数的时候,接收两个参数,(dispatch, props),它的目的是确定组件如何发送action。const mapDispatchToProps = (dispatch)=>{
return {
handleSave:(err, values)=>{
const action = actionCreator.getSaveAction(err, values);
dispatch(action)
},
getCate:(parendCategoryId, CategoryId)=>{
const action = actionCreator.Action(Id,CateId);
dispatch(action)
}
}
}组件中调用handleSave方法出发dispatch方法,dispatch 传递一个action给Store,进而完成数据的更新。action 就是包含一个type属性为唯一的类型。在reducer 文件中,根据action的type来进行相应的数据更新操作。export default (state=defaultState,action)=>{
if(action.type === types.PAGE_DONE){
return state.set(‘isPageFetching’,false)
}
if(action.type === types.SHOW_UPDATE_CANCEL){
return state.set(‘updateModelVisible’,false)
}
if(action.type == types.SHOW_UPDATE_NEWNAME){
return state.set(‘updateName’,action.payload)
}
return state
}`
相关文章: