歡迎關注公衆號:n平方
若有問題或建議,請後臺留言,我會盡力解決你的問題。
Redux是針對JavaScript應用的可預測狀態容器。html
若是熟悉設計模式之觀察者模式理解起來就簡單了。就是將你在其餘組件中須要用到的數據放到一個容器中,那麼組件就能夠從其中取放數據的東西就是redux的工做。
特性:react
action:是把數據從應用(譯者注:這裏之因此不叫 view 是由於這些數據有多是服務器響應,用戶輸入或其它非 view 的數據 )傳到 store 的有效載荷。它是 store 數據的惟一來源。通常來講你會經過 store.dispatch() 將 action 傳到 store。git
reducer:指定了應用狀態的變化如何響應 actions,併發送到 store 的,記住 actions 只是描述了有事情發生了這一事實,並無描述應用如何更新 state。 github
store: store就是把action和reducer聯繫到一塊兒的對象,store本質上是一個狀態樹,保存了全部對象的狀態。任何UI組件均可以直接從store訪問特定對象的狀態。
Store 有如下職責:npm
getState()
方法獲取 state;dispatch(action)
方法更新 state;subscribe(listener)
註冊監聽器;subscribe(listener)
返回的函數註銷監聽器。再次強調一下 Redux 應用只有一個單一的 store。redux
這個數據流的位於最中心的設計是一個AppDispatcher(應用發送器),你能夠把它想成是個發送中心,不論來自組件何處的動做都須要通過它來發送。每一個store會在AppDispatcher上註冊它本身,提供一個callback(回調),當有動做(action)發生時,AppDispatcher(應用發送器)會用這個回調函數通知store。設計模式
因爲每一個Action(動做)只是一個單純的對象,包含actionType(動做類型)與數據(一般稱爲payload),咱們會另外須要Action Creator(動做建立器),它們是一些輔助函數,除了建立動做外也會把動做傳給Dispatcher(發送器),也就是調用Dispatcher(發送器)中的dispatch方法。api
Dispatcher(發送器)的用途就是把接收到的actionType與數據(payload),廣播給全部註冊的callbacks。它這個設計並不是是首創的,這在設計模式中相似於pub-sub(發佈-訂閱)系統,Dispatcher則是相似Eventbus的概念。服務器
安裝併發
npm install --save react-redux npm install --save-dev redux-devtools
實例
主要是理解觀察者模式,以及結合原理圖先理解
redux的action,reducer,store基本運做。
import { createStore } from 'redux' /** * This is a reducer, a pure function with (state, action) => state signature. * It describes how an action transforms the state into the next state. * * The shape of the state is up to you: it can be a primitive, an array, an object, * or even an Immutable.js data structure. The only important part is that you should * not mutate the state object, but return a new object if the state changes. * * In this example, we use a `switch` statement and strings, but you can use a helper that * follows a different convention (such as function maps) if it makes sense for your * project. */ /** * 來源:官網:https://github.com/reduxjs/redux * * 第一步:定義reducer */ function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: return state } } // Create a Redux store holding the state of your app. // Its API is { subscribe, dispatch, getState }. //第二步:根據reducer規則生成store let store = createStore(counter) // You can use subscribe() to update the UI in response to state changes. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly. // However it can also be handy to persist the current state in the localStorage. //第三步:定義數據(即state)變化以後的派發規則 store.subscribe(() => console.log(store.getState())) store.subscribe(() => console.log(store.getState())) store.subscribe(() => console.log(store.getState())) // The only way to mutate the internal state is to dispatch an action. // The actions can be serialized, logged or stored and later replayed. //第四步:觸發數據變化 store.dispatch({ type: 'INCREMENT' }) // 1 store.dispatch({ type: 'INCREMENT' }) // 2 store.dispatch({ type: 'DECREMENT' }) // 1
通常的文件結構,基本就是store目錄下
actions的操做
user.js:主要包含user模塊下的action操做。
import * as types from '../constants/types' export function loginSuccess(data) { return { type: types.LOGOIN_SUCCESS, payload: data } } export function logOut() { return { type: types.LOGOUT } }
reducers的操做
module/user.js:定義
import * as types from '../../constants/types'; export function user(state = 0,action){ switch(action.type) { case types.LOGOIN_SUCCESS: console.log("user......"+ action.payload); return state+10; case types.LOGOUT: return state - 10; default: return state; } }
index.js
將全部reducers的集合在一塊兒。
import { combineReducers } from 'redux' import { user } from './module/user' const rootReducer = combineReducers({ /* your reducers */ user }) export default rootReducer
store的操做
import { createStore } from 'redux' import rootReducer from './reducers' export default function configureStore(initialState) { const store = createStore(rootReducer,initialState, window.devToolsExtension ? window.devToolsExtension() : undefined ) return store }
組件中的操做(簡單)
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import ComA from './ComA' import ComB from './ComB' import * as userInfoActions from '../store/actions/user' class BodyIndex extends React.Component { componentDidMount() { this.props.userInfoActions.loginSuccess({ id:'呵呵呵呵', username: 'bibibiibibi' }) } render() { return ( <div> <p>Hello world</p> <ComA user={this.props.user}/> <ComB user= {this.props.user} /> </div> ) } } function mapStateToProps(state) { console.log("mapStateToProps...."+state); return { user: state.user.userInfo } } function mapDispatchToProps(dispatch) { return { userInfoActions: bindActionCreators(userInfoActions,dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(BodyIndex)
組件中的操做(常規)
使用connect 這樣子能夠省去mapDispatchToProps,mapDispatchToProps的操做。
import React from 'react'; import { connect } from 'react-redux'; import { addComment } from '../store/actions/comment' @connect( state => ({comment:state.comments.comment}), { addComment } ) class TestCom extends React.Component { componentDidMount() { this.props.addComment({ comment: 100 }) } render() { console.log("render...."+this.props.comment); return ( <div> <p>TestCom.... {this.props.comment} </p> </div> ) } } export default TestCom;
最後,若是對 Java、大數據感興趣請長按二維碼關注一波,我會努力帶給大家價值。以爲對你哪怕有一丁點幫助的請幫忙點個贊或者轉發哦。