Redux 學習筆記(二)

2021-07-17 02:30:20 字數 2740 閱讀 7932

要將 redux 和 react 結合起來使用,就還需要一些額外的工具,其中最重要的是 react-redux 。

react-redux 提供了兩個重要的物件,provider 和 connect,前者使 react 元件可被連線(connectable),後者把 react 元件和 redux 的 store 真正連線起來。

通過 reducer 建立乙個 store,每當我們在 store 上 dispatch 乙個 action,store 內的資料就會相應地發生變化。

const reducer = (state = , action) => ;

case 'decrease': return ;

default: return state;

}}const actions = ),

decrease: () => ()

}const store = createstore(reducer);

store.subscribe(() =>

console.log(store.getstate())

);store.dispatch(actions.increase()) //

store.dispatch(actions.increase()) //

store.dispatch(actions.increase()) //

在最外層容器元件中初始化 store,然後將 state 上的屬性作為 props 層層傳遞下去。

componentwillmount()

render()

ondecrease=

/>

}}首先在最外層容器中,把所有內容包裹在 provider 元件中,將之前建立的 store 作為 prop 傳給 provider。

return (

)};provider 內的任何乙個元件(比如這裡的 comp),如果需要使用 state 中的資料,就必須是「被 connect 過的」元件——使用 connect 方法對「你編寫的元件(mycomp)」進行包裝後的產物。

class mycomp extends component 

const comp = connect(...args)(mycomp);

connect([mapstatetoprops], [mapdispatchtoprops], [mergeprops], [options])

connect() 接收四個引數,它們分別是 mapstatetoprops,mapdispatchtoprops,mergeprops和options

將 store 中的資料作為 props 繫結到元件上。

const mapstatetoprops = (state) => 

}

這個函式的第乙個引數就是 redux 的 state,我們從中摘取了 count 屬性。因為返回了具有 count 屬性的物件,所以 mycomp 會有名為 count 的 props 字段

class mycomp extends component 次

}}const comp = connect(...args)(mycomp);

不必將 state 中的資料原封不動地傳入元件,可以根據 state 中的資料,動態地輸出元件需要的(最小)屬性。

const mapstatetoprops = (state) => 

}

將 action 作為 props 繫結到 mycomp 上。

const mapdispatchtoprops = (dispatch, ownprops) => 

}class mycomp extends component = this.props;

return (計數:次

增加減少

) }

}const comp = connect(mapstatetoprops, mapdispatchtoprops)(mycomp);

由於 mapdispatchtoprops 方法返回了具有 increase 屬性和 decrease 屬性的物件,這兩個屬性也會成為 mycomp 的 props。

呼叫 actions.increase() 只能得到乙個 action 物件 ,要觸發這個 action 必須在 store 上呼叫 dispatch 方法。diapatch 正是 mapdispatchtoprops 的第乙個引數。

為了不讓 mycomp 元件感知到 dispatch 的存在,將 increase 和 decrease 兩個函式包裝一下,使之成為直接可被呼叫的函式(即,呼叫該方法就會觸發 dispatch)。

redux 本身提供了 bindactioncreators 函式,來將 action 包裝成直接可被呼叫的函式。

import  from 'redux';

const mapdispatchtoprops = (dispatch, ownprops) => );

}

根據connect的api我們發現可以使用es7 decorator功能來配合react es6的寫法:

@connect(

state => (),

dispatch => (, dispatch)

}))export default class main extends component

Redux 學習筆記(二)

高階元件 簡單的說,高階元件就是乙個函式,這個函式接收乙個元件作為輸入,返回乙個元件作為結果,因此,新返回的元件擁有了輸入元件所不具備的功能。import react from react render this.props export default removeuserprop const n...

reatc學習筆記(二) redux

react的狀態管理,類似於vue的vuex 不同點是 redux可以不依賴react使用,react沒有redux也可以使用,vuex必須依賴vue使用 公共的共享資料 redux渲染流程 reducer為更改store裡資料的東西,通過reducer去和state互動 流程為 store.get...

redux學習筆記

流程如下 在redux中使用者的操作並不會直接導致view層的更新,而是view層發出actions通知出發store裡的reducer從而來更新state state的改變會將更新反饋給我們的view層,從而讓我們的view層發生相應的反應給使用者。redux中有三個基本概念,action,red...