首先差別redux和react-reduex,redux是一個單獨的子產品,在其他架構中也能使用,而react-redux是為react管理資料而生。 Redux 的設計思想很簡單,就兩句話。
(1)Web 應用是一個狀态機,視圖與狀态是一一對應的。
(2)所有的狀态,儲存在一個對象裡面。
redux使用:首先安裝 npm i redux 在src檔案目錄下建立一個檔案夾叫redux,檔案夾中建立四個檔案
constant.js 用于存儲action對象中的type類型常量,目的隻有一個;友善管理的同時防止程式員單詞寫錯,
例如:
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
action.js 該檔案專門為元件生成action對象
import {INCREMENT,DECREMENT} from './constant'
//同步action,就是指action的值為Object類型的一般對象
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})
//異步action,就是指action的值為函數,異步action中一般都會調用同步action,異步action不是必須要用的。
export const createIncrementAsyncAction = (data,time)=>{
return (dispatch)=>{
setTimeout(()=>{
dispatch(createIncrementAction(data))
},time)
}
}
reducer.js
/*
1.該檔案是用于建立一個為Count元件服務的reducer,reducer的本質就是一個函數
2.reducer函數會接到兩個參數,分别為:之前的狀态(preState),動作對象(action)
*/
const initState = 10 //初始化狀态
export default function countReducer(preState=initState,action){
console.log(preState,action);
//從action對象中擷取:type、data
const {type,data} = action
//根據type決定如何加工資料
switch (type) {
case 'increment': //如果是加
return preState + data
case 'decrement': //若果是減
return preState - data
default:
return preState
}
}
store.js 該檔案專門用于暴露一個store對象,整個應用隻有一個store對象 要下載下傳 npm i redux-thunk --save
//引入createStore,專門用于建立redux中最為核心的store對象,引入applyMiddleware中間件轉發
import {createStore,applyMiddleware} from 'redux'
//引入為Count元件服務的reducer
import countReducer from './reducer'
// 引入redux-thunk,用于支援異步action
import thunk from 'redux-thunk';
//暴露store
export default createStore(countReducer,applyMiddleware(thunk));
最後在index.js檔案中引入store并設定監聽
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App />,document.getElementById('root'))
store.subscribe(()=>{ //設定監聽,隻要state改變資料頁面就會更新
ReactDOM.render(<App/>,document.getElementById('root'))
})
// 引入store,用于擷取redux中儲存狀态
import store from '../../redux/store'
// 操作異步資料 引入相應的action函數
import {createIncrementAsyncAction} from '../../redux/action'
increment = ()=>{ //同步函數的調用
const {value} = this.selectNumber
store.dispatch({type:'increment',data:value*1})
}
incrementAsync = ()=> {//異步函數的調用
const {value} = this.selectNumber;
store.dispatch(createIncrementAsyncAction(value*1,500))
}
<h1>目前求和為:{store.getState()}</h1>//擷取store中的傳回值
不停學習,熱愛是源源不斷的動力。