redux核心概念: store,state,action,reducercss
首先經過reducer新建store,經過store.getState()獲取狀態react
須要狀態變動,store.dispatch(action) 來修改redux
reducer函數接受state和action,返回新的state,能夠用store.subscribe監聽每次的修改dom
import { createStore } from 'redux' function reducer(state=10, action){ switch (action.type) { case 'ADD': return state + 1 case 'CUT': return state - 1 default: return 10 } } // 建立一個store createStore中傳入的必須是一個函數 let store = createStore(reducer) let init = store.getState() console.log('一開始數據------', init) function listener() { let cur = store.getState() console.log('cur------', cur) } // 訂閱,每次state修改,都會執行listener store.subscribe(listener) //提交狀態變動 store.dispatch({type: 'ADD'}) store.dispatch({type: 'ADD'}) store.dispatch({type: 'CUT'})
redux如何跟react一塊兒使用svg
index.js中函數
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { createStore } from 'redux' import {counter, add, cut} from './redux' const store = createStore(counter) function init (){ ReactDOM.render(<App store={store} add={add} cut={cut} />, document.getElementById('root') ); } init () store.subscribe(init)
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { let store = this.props.store return ( <div className="App"> <h3>redux中默認的store.getState()的值爲 <span>{store.getState()}</span> </h3> <button onClick={()=>{ store.dispatch(this.props.add()) }}>按鈕 + 1</button> <button onClick={()=>{ store.dispatch(this.props.cut()) }}>按鈕 - 1</button> </div> ); } } export default App;