redux
是js的狀態容器,提供可預測的狀態管理,同時可運行於不一樣的環境而且還有redux-devtools
供可視化調試,大型應用下有良好的跨組件通信與狀態管理是必不可少的,那麼就在本章中探索redux
是如何與react
串聯,並是如何使用redux
javascript
$ npm or cnpm $ npm install redux react-redux
相信有很多人都比較好奇 爲何我已經有了redux
還要再多引入一個react-redux
實際上這樣是爲保證核心功能最大程度上的跨平臺複用
首先新建一個文件夾store
用來存放redux的配置及相關文件,看一下store
中的文件結構java
. ├── actions │ └── index.js ├── index.js └── reducers └── index.js 2 directories, 3 files # 其中最外層的index.js是主要的配置文件
在react的入口文件index.js
中引入react-redux
react
Provider是react-redux兩個核心工具之一,做用:將store傳遞到項目的組件中,並能夠在組件中使用redux
import
通常引入文件夾會默認找到該文件夾中的index.js
git
import { applyMiddleware, createStore } from 'redux' import thunk from 'redux-thunk' import reducers from './reducers/index' let store = createStore( reducers, applyMiddleware(thunk) ) export default store
redux
中以createStore
建立store並在其中插入reducers
與中間件,redux-thunk
是爲了加強action
在原生的redux
中action
只能返回對象,可是加上這個中間件就能夠返回一個函數而且能夠訪問其餘actiongithub
// 測試action function test (text) { return { type: 'test', text: text } } export default { test }
import { combineReducers } from 'redux' const Initstate = { // 初始狀態 } const Common = (state = Initstate, action) => { switch (action.type) { case 'test': return {...state, test: action.text} default: return state } } let reducer = combineReducers({ Common: Common }) // 注意combineReducers是用於合併多個reducer 當所用模塊很少,協做少時 能夠不用
從reducer中咱們就能夠發現redux的三大原則:1.
單一數據源
: 所謂的單一數據源是隻有一個Model
雖然咱們能夠定義多個reducer
可是通過combineReducers
整合發現 全部的Model
都存在一個大的JSON裏面npm2.
狀態是隻讀
: 咱們能夠發現當咱們接收到名爲test
的變化時;並非修改Initstate
而是?> 直接返回state
至關於只是讀取這個默認狀態並與action
中返回的狀態整合 redux3.
狀態修改均有純函數完成
:能夠發現common
這個函數實用switch
接收到必定的action.type
就會返回相應的屬豬bash
以App.jsx示例
import React, { Component } from 'react' import { connect } from 'react-redux' import Action from ‘./../store/actions/index’ class App extends Component { test () { this.props.test(‘test’) // 測試數據 } render () { return ( <div> { this.props.test } {/*測試數據*/} </div> ) } } const mapStateToProps = (state) => { return { test: state.Common.test } } const mapDispatchToProps = (dispatch, ownProps) => { return { test: (data) => dispatch(Action.test(data)) } } export default connect(mapStateToProps, mapDispatchToProps)(App)
mapStateToProps: 這個函數的主要主要做用在與把modal
中的狀態與該組件的props
進行融合以致於組件能夠直接經過this.props.test
訪問到modal
中的狀態mapDispatchToProps: 這個函數的主要做用是把
action
中的函數經過dispatch
分發一個action
到reducer
並把action
函數合併到該組件中的props
app
Blog_demo 本文redux_demo ide
關於在react項目中如何使用redux,以及具體寫法,個人分層方式這些都在此文中有所展示。可是這只是剛接觸時,個人一些思路,還有一些有趣的東西我會在後續中說起(router 與 redux 綁定 ,middleware 的基本原理等)若是各位大佬有更好的思路請在留言告訴我,不勝感激