前言
好久沒有更新博客了冈在,前段時間一直在準(zhǔn)備春招瓷产,幸運(yùn)的是能入職一家不錯的公司站玄,公司的技術(shù)棧是react,所以得轉(zhuǎn)react濒旦,希望以后學(xué)習(xí)的過程中能多更新文章株旷,學(xué)會知識最好的辦法就是給別人講懂。
一尔邓、Redux介紹
Redux 是針對 JavaScript 應(yīng)用程序的可預(yù)測狀態(tài)容器晾剖。
它可以幫助您編寫性能一致、在不同環(huán)境(客戶端铃拇、服務(wù)器和原生環(huán)境)中運(yùn)行且易于測試的應(yīng)用程序钞瀑。最重要的是,它提供了出色的開發(fā)人員體驗(yàn)慷荔,例如 帶有時間旅行調(diào)試器的實(shí)時代碼編輯雕什。
可以將 Redux 與 React 或任何其他類似的工具庫一起使用。 他的體積很邢跃А(算上依賴也只有 2kB)贷岸,但是在其生態(tài)系統(tǒng)中有大量插件可用。
以上是官網(wǎng)的解釋磷雇,其實(shí)就和Vuex是一個狀態(tài)管理器偿警,用來在構(gòu)建大型應(yīng)用的時候組件之間可以共享全局?jǐn)?shù)據(jù)。因?yàn)槿绻麡I(yè)務(wù)過于復(fù)雜組件之間數(shù)據(jù)傳遞可能會很麻煩唯笙。就像這樣螟蒸,左邊是沒有 redux盒使,右邊是有 redux。
二七嫌、Redux工作流程
首先放張圖片感受一下
2.1 redux 安裝
npm安裝
npm install --save redux
2.2 redux基本使用
我們可以看到 React Components
是從 Store
里面拿數(shù)據(jù)的少办,那么我們可以初步得出結(jié)論,Store
就是數(shù)據(jù)管理中心诵原,所有的全局?jǐn)?shù)據(jù)就是存在這里面的英妓,下面我們來使用一下。
我們在 react
項(xiàng)目中 src
文件中新建 store
文件夾下面新建兩個文件分別為 index.js
reducer.js
大致目錄如下
--src
----store
------index.js
------reducer.js
----index.js
----TodoList.js
// store/reducer.js
const defaultState = {
inputValue: '',
data: [
{ id: 1, title: '吃飯', compeled: false },
{ id: 2, title: '睡覺', compeled: false },
{ id: 3, title: '打豆豆', compeled: false }
]
}
//eslint-disable-next-line
export default (state = defaultState, action) => {
// console.log(action)
// Reducer里面只能接收state 不能改變state
if(action.type === 'CHANGE_INPUT'){
let newValue = JSON.parse(JSON.stringify(state))
newValue.inputValue = action.value
return newValue
}
if(action.type === 'ADD_ITEM'){
let newValue = JSON.parse(JSON.stringify(state))
if(newValue.inputValue === '') return newValue
let item = {
id:new Date().getTime(),
title:newValue.inputValue,
compeled:false
}
newValue.data.push(item)
newValue.inputValue = ''
return newValue
}
if(action.type === 'DELETE_ITEM'){
let newValue = JSON.parse(JSON.stringify(state))
let index = newValue.data.findIndex(item => item.id === action.id)
newValue.data.splice(index,1)
return newValue
}
return state
}
// store/index.js
import {createStore} from 'redux'
import reducer from './reducer'
// reducer (state,action) => {}
const store = createStore(reducer)
export default store
這里我們看到創(chuàng)建 store
對象其實(shí)調(diào)用了 redux
中的 createStore
方法绍赛,它的參數(shù)就是一個函數(shù)蔓纠,我們這里就是 reducer
,它里面有 state
和 action
兩個參數(shù)吗蚌。state
我們初始化了值腿倚。而我們的 action
這里是什么呢?
我們看看TodoList.js
的代碼褪测,我們通過引入創(chuàng)建的 store
通過 store.getState()
獲取數(shù)據(jù)猴誊。
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Button, Input, List } from 'antd'
import store from './store'
class TodoList extends Component {
constructor(props) {
super(props);
//獲取數(shù)據(jù)
this.state = store.getState()
// 監(jiān)聽數(shù)據(jù)改變 更新state
store.subscribe(this.storeChange)
}
deleteItem = (id) => {
// console.log(id)
const action = {
type:'DELETE_ITEM',
id
}
// 刪除item
store.dispatch(action)
}
handleInputValue = (e) => {
const action = {
type:'CHANGE_INPUT',
value:e.target.value
}
//改變inputvalue
store.dispatch(action)
}
clickBtn = () => {
const action = {
type:'ADD_ITEM'
}
// 添加item
store.dispatch(action)
}
storeChange = () => {
this.setState(store.getState())
}
render() {
return (
<div style={{margin:'15px'}}>
<div>
<Input
placeholder='Write Something'
style={{width:'250px',marginRight:'15px'}}
onChange={this.handleInputValue}
value={this.state.inputValue}
/>
<Button
type='primary'
onClick={this.clickBtn}
>Add</Button>
</div>
<div style={{marginTop:'15px',width:'250px'}}>
<List
bordered
dataSource={this.state.data}
renderItem={item => (<List.Item onClick={this.deleteItem.bind(this,item.id)}>{item.title}</List.Item>)}
/>
</div>
</div>
);
}
}
export default TodoList;
這里的 action
就是我們通過 store.dispatch(action)
方法傳遞的一個個事件,這里 action
對象必須有一個 type
屬性, 用來告訴 redux 你是干嘛的侮措。然后我們通過 reducer
回調(diào)來更新相應(yīng)數(shù)據(jù)懈叹。這里注意一下: reducer里面只能接收 state 不能改變state,所以我們可以看到上面是先拷貝數(shù)據(jù),更新之后再返回分扎,并不是直接更新 state 數(shù)據(jù)
那么我們可以根據(jù)上面的流程圖初步了解redux的執(zhí)行流程澄成,首先通過 redux
的 createStore
函數(shù)創(chuàng)建一個 store
對象,注意這里函數(shù)的參數(shù)是個回調(diào)函數(shù) reducer
畏吓。我們 react components
通過 store.getState()
獲取數(shù)據(jù)墨状,如果遇到變更的情況,我們需要通過 store.dispatch(action)
(action{type:'TYPE',value:'value'}
) , 來告知 store
做出改變菲饼,怎么做出改變呢肾砂?我們看到數(shù)據(jù)通過 React Components
出發(fā)到 Action Creators
再到 Store
最終到 Reducers
進(jìn)行處理的。那么我們上面的代碼也可以清楚的展示 reducer 回調(diào)函數(shù)里面處理各種 dispatch(action)
的邏輯宏悦。處理之后的 newState
更新到 Store
數(shù)據(jù)倉庫
為了閱讀方便镐确,再次放送此圖。
為了demo完整性饼煞,這里將 src/index.js 代碼貼上
import React from 'react'
import ReactDom from 'react-dom'
import TodoList from './TodoList'
ReactDom.render(
<TodoList />,
document.getElementById('root')
)
這里redux最簡單的使用就差不多了介紹完了源葫。后面會持續(xù)更新一些高級的用法,喜歡記得點(diǎn)點(diǎn)關(guān)注砖瞧。