react-redux基本使用和数据流向

    技术2022-07-11  91

    react的状态管理工具react-redux

    我们先来看一下react-redux的工作流程

    redux的组成部分

    redux简单的来说他分为这几个部分

    statereduceracitonstore

    state:如果你熟悉vuex的话你可以把他当成vuex里面的模块化,相当于数据树的一个分支或者总体。

    const State = { imgList:[] }

    reducer:通过传入的aciton去改变state的值,并且向外面暴露辅助生成store。

    const reducer = (state = State,action)=>{ switch(action.type){ case 'ADD_IMGLIST': return { ...state, imgList:action.data } default : return state } } export default reducer

    aciton:通过dispatch一个action来进入reducer,在reducer中获取action的type去更改state。

    dispacth({ type:'ADD_IMGLIST', data })

    store : 使用createStore方法把reducer生成一个store,store会在根据connect方法解析为props放在组件中。

    const store = createStore(reducer) let reducer = combineReducers({ feedBack })

    如何在把数据放在react组件中?

    如果不使用react-redux的话,那么react自带的context绝对是最好的方法。react-redux中可以解析出provide,把store当做props使数据向下传递。但是注意一定要放在跟组件内,因为要全局通讯,从这里我们可以看出来了redux和react的强耦合的关系。

    ReactDOM.render( <Provider store={store}> <App/> </Provider>, document.getElementById('root') );

    如何把数据在react中拿到?

    使用context的话可以在Consumer中拿到然后渲染,react-redux中也有Consumer方法,另外他还有更好的支持就是connct方法

    const mapstatetoprops = (state)=>{ return { imglist:state.feedBack.imgList } } const mapdispatchtoprops = (dispacth)=>{ return { addImgList(data){ dispacth({ type:'ADD_IMGLIST', data }) } } } //手写两个静态方法,名字中我们可以看出是state和dispatch到props的映射关系 connect(mapstatetoprops,mapdispatchtoprops)(组件名称) //最后通过传入这两个方法,然后包裹组件暴露在外面,以上方法和props我们可以直接使用 this.props.addImgList() this.props.imglist //获取值或者调用方法。

    数据流向文字描述

    创建state来存储公共数据,使用reducer来进行对state的改变,store把reducer封装作为数据源放在react的props中,在组件内触发方法disptch一个action,action中含有状态和data,reducer接收状态进行对state的改变,从而react的view层进行重新渲染。

    Processed: 0.013, SQL: 9