redux是一个提供组件之间数据共享,管理处理的模块,在react组件中使用十分普遍,如何在react组件中实现数据共享管理?react
1.利用store存储数据信息,利用store.getState()获得当前的状态值
导入redux中的createStore方法,建立一个storeredux
import {createStore} from 'redux' const store = createStore()
2.state是store某一个时刻的数据值,store里面的数据变动会触发store.subscribe中回调函数,在里面设置setState引起view更新
3.定义action类型type和携带的数据,action是一个对象里面必须有type属性,它标识了action类型名称,也能够用函数生成actiondom
const action= { type: 'CHANGE', data:'data' } //another way to create a action with function function actionsCreator(obj) { return { type: 'CHANGE', name: obj.name, pass: obj.pass } }
4.view中触发store改变。store.dispatch(action)给dispatch方法传入action来更新store中数据(dispatch是触发更新,action是定义更新类型,action相似于定义domEvent中的事件类型click 、onload、onchange······有不少类型,可是触发还须要调用store.dispatch)
5.在createStore中传入一个函数做为参数(必须),这个函数是reducer,定义dispatch某个action后state针对这个action如何更新.
reducer(initialState,action)。因为它的功能是根据初始state和action类型生成更新后的state,它接收初始initialState,action做为参数函数
功能
两个组件一个UShow 一个UInput
二者之间共享redux >store里面的数据,一个用来展现,一个用来改变store里面的数据。
方法步骤this
util/redux.js
文件存放store共有数据,相关代码1.定义storespa
//redux.js import {createStore} from 'redux' const store = createStore(reducer)
2.定义某个action被dispatch后的state变化规则(这个代码必须在createStore定义store前面)
下面代码含义为若是acttion类型是CHANGE那么就返回action对象中的name和pass,借此更新statecode
const reducer = (initialState = { name: 'mayun', pass: 'asd' }, actions) => { switch (actions.type) { case 'CHANGE': return { name: actions.name, pass: actions.pass } default: return initialState } }
3.定义action对象,即什么类型的action会被分发,也能够在其中携带用户自定义的数据(咱们定义的是pass和name)。这里咱们用一个函数来生成这个action对象,本质和直接定义action对象没啥区别对象
function actionsCreator(obj) { return { type: 'CHANGE', name: obj.name, pass: obj.pass } } export { actionsCreator ,const store}
4.用store.subscribe()触发view更新(在子组件UShow中实现)。blog
定义一个MyWrap组件做为容器,定义UInput UShow做为它的子组件事件
const MyWrap=()=>( <div> <UInput></UInput> <UShow></UShow> </div> ) ReactDOM.render(<MyWrap></MyWrap>,document.getElementById('example'))
获取store数据。在子组件UShow 构造函数constructor中订阅state变化,设置回调函数赋值给this.state实视图更新
class Ushow extends React.Component{ constructor(...args){ super(...args) this.state={ name:'匿名', pass:'空密码' } store.subscribe(()=>{ this.setState({ name:store.getState().name, pass:store.getState().pass }) }) } render(){ return ( <div> name:<span>{this.state.name}</span> pass:<span>{this.state.pass}</span> </div> ) } }
view UInput中更新store。利用dispatch在UInput 中dispatch 某个action到store(数据携带在action对象的其余属性里),把数据更新从视图view传递到store
class UInput extends React.Component{ sure(){ store.dispatch(actionsCreator({name:this.refs.name.value,pass:this.refs.pass.value})) } render(){ return( <div> <div> 姓名:<input ref="name" type="text"/> 密码:<input ref="pass" type="text"/> <button onClick={this.sure.bind(this)}>登陆</button> </div> </div> ) } }
必定要在目录中导入redux文件import {store ,actionsCreator} from '../util/redux.js'
这样就能够用原生redux实现react组件之间数据共享。