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組件之間數據共享。