react-redux? 中文文檔? ?https://www.redux.org.cn/docs/react-redux/api.html
在使用redux 的時候? 需要引入? redux? react-redux
npm install --save redux
npm intsall --save react-redux
第一步:
創(chuàng)建 reducer ,?Reducers?指定了應用狀態(tài)的變化如何響應?actions?并發(fā)送到 store 的 ,
reducer? 是用來管理 state,根據(jù)不同的action? 返回不同的值
應用很大的時候需要拆分 reducer , 最后合并成一個 根reducer
這里就需要用到 combineReducers? 函數(shù)
最后:把根rootReducer 暴露給 store
第二步:
創(chuàng)建? store? ?store?來存放所有的 state癞志。應用中僅有一個 store
通過函數(shù) createStore? 創(chuàng)建 store ,如果使用中間鍵,則需要引入?applyMiddleware 函數(shù)
最后 : 把store 暴露出去? 在index.js? 文件總引入 配置全局的 store
第三步:
? 在index.js? 文件中 引入 store , 配置全局store 還需要 引入 Provider?
第四步:
創(chuàng)建 action :?
這里action? 為了方便管理 增加了一個contants 文件夾? 把 type? 定義進去? 再引入過來
第五步:
在頁面中 引入 connect,??
import { connect } from 'react-redux';
connect? 有四個參數(shù)
mapStateToProps : 用來更新 state? 以便頁面中使用
mapDispatchToProps :? 可以定義函數(shù) 直接 觸發(fā)action type? ?如下:
比較這三種寫法可以看出 :?
第一種? :
是 通過 mapDispatchToProps? 函數(shù)? 把 increment 方法? 放入props中,
在調用時increment?? 通過mapDispatchToProps 自帶的dispatch 直接觸發(fā) action??
第二種 :?
直接引入action? 中的方法 狭莱,放入connect 中,實現(xiàn)方法放入props里,再通過調用
props中的方法觸發(fā)action
第三種 :?
引入所有的action 魁索,通過bindActionCreators? 函數(shù)? 把每個action 都增加 dispatch 屬性
通過調用props 中的方法 觸發(fā)action
這是有緩存的時候這么用? 一般情況寫正常寫就可以了? 這些不必要加