手把手教會你使用redux的入門教程
Redux詳解
Redux介紹
Redux 是 JavaScript 應用的狀態(tài)容器,提供可預測的狀態(tài)管理。
在Redux中有3個原則
單一數(shù)據(jù)源
整個應用的
State被儲存在一棵 object tree 中,并且這個 object tree 只存在于唯一一個Stroe中。State 是只讀的
唯一改變
State的方法就是觸發(fā)Actions,Actions是一個用于描述已發(fā)生事件的普通對象。使用純函數(shù)來執(zhí)行修改
為了描述
Actions如何改變 State tree ,你需要編寫Reducers。
如下圖所示,在Redux中,有一個全局狀態(tài)存儲器Store,只有Actions才能去進行修改Store中的數(shù)據(jù),其更改數(shù)據(jù)這一過程,即store.dispatch(action)就是為Reducers。當Actions修改完Store中的數(shù)據(jù)后,Store會通知對應頁面其數(shù)據(jù)發(fā)送改變。

Redux有什么作用
得益于react是單項數(shù)據(jù)流的關系,在react框架中要統(tǒng)籌全局數(shù)據(jù)就顯得較為繁瑣,需要通過父子間的組件傳遞/或者是Context才能進行跨組件交流,但在react里,context是個反模式的東西,不同于redux等的細粒度響應式更新,context的值一旦變化,所有依賴該context的組件全部都會force update,因為context API并不能細粒度地分析某個組件依賴了context里的哪個屬性,并且它可以穿透React.memo和shouldComponentUpdate的對比,把所有涉事組件強制刷新。
Context 設計目的是為了共享那些對于一個組件樹而言是“全局”的數(shù)據(jù),例如當前認證的用戶、主題或首選語言。
如何在React中使用Redux
React中使用的是react-redux這個三方包
這里借用下大佬圓兒圈圈繪制的流程圖,大致流程如下

react-redux中的connect方法將store上的getState 和 dispatch 包裝成組件的props。
如何使用React-redux
舉個todoList的栗子
在需要共享數(shù)據(jù)的主入口,先引入redux和react-redux,再引入 createStore 來創(chuàng)建組件共享的數(shù)據(jù),這個是 redux 中提供的一個方法,我們直接引入,并將主入口文件用Provider包裹一下。
import React, { Component } from 'react';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import reducer from './redux/reducer/index'
import AddItemPage from './components/index'
const store = createStore(reducer) //使用createStore創(chuàng)建個store
export default class App extends Component {
render() {
return (<Provider store={store}> //todoList共享store
<AddItemPage/> //todoList頁面
</Provider>)
}
}然后去定義action和reducer的初始狀態(tài),因為在reducer中已經(jīng)設置了state的初始值為[],故不作定義state
reducer的
import { combineReducers } from 'redux'
?
const addItem = (state = [], action) => {
switch (action.type) {
case 'ADD_ITEM':
return [
...state,
{
id: action.id,
text: action.text,
isDelete: false
}
]
case 'DELETE_ITEM':
let newState = [...state]
console.log(newState)
action.id.map(item=>{
newState.splice(item.id,1)
})
return newState
default:
return state
}
}
export default combineReducers({
addItem
})action
let nextItemId = 0
export const addTodo = text => ({
type: 'ADD_ITEM',
id: nextItemId++,
text
})
?
export const deleteItem = id => ({
type: 'DELETE_ITEM',
id
})然后再模塊中將定義的action以及reducer返回的state鏈接到模塊中
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { addTodo,deleteItem } from '../redux/action'
import ItemList from './itemList'
?
class AddItem extends Component {
render() {
const { addItem,doAdd,doDelete } = this.props
return <>
<div>
<form onSubmit={e => {
e.preventDefault()
if (!this.input.value.trim()) {
return
}
doAdd(this.input.value)
// this.props.dispatch(addTodo(this.input.value))
this.input.value = ''
}}>
<input ref={node => this.input = node} />
<button type="submit">
添加
</button>
<button type="button" onClick={(e)=>{
let arr = []
const checkbox = document.getElementsByName('itemId').forEach(item=> {
if(item.checked) arr.push(item.value)
})
doDelete(arr)
// this.props.dispatch(deleteItem(arr))
}}>
刪除
</button>
</form>
</div>
<ItemList addItem={addItem}/>
</>
}
}
const mapStateToProps = state => {return ({...state})}
const mapDispatchToProps = dispatch => ({
doAdd:(value)=>dispatch(addTodo(value)),
doDelete:(arr)=>dispatch(deleteItem(arr))
})
?
export default connect(
mapStateToProps,
mapDispatchToProps
)(AddItem)import React, { Component } from 'react';
class itemList extends Component {
render() {
return <>
{
this.props.addItem.map(item=>{
return <div key={item.id} {...item}>
<input type='checkbox' name='itemId' value={item?.id}/>
<li
style={{
textDecoration: item?.completed ? 'line-through' : 'none'
}}
>
{item?.text}
</li>
</div>
})
}
</>;
}
}
?
export default itemList即可,
可以看到輸入123,點擊添加的時候觸發(fā)了ADD_ITEM的操作

點擊刪除的時候觸發(fā)了DELETE_ITEM操作

到此這篇關于手把手教會你使用redux的入門教程的文章就介紹到這了,更多相關redux入門內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于JavaScript實現(xiàn)前端數(shù)據(jù)多條件篩選功能
這篇文章主要為大家詳細介紹了基于JavaScript實現(xiàn)前端數(shù)據(jù)多條件篩選功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
JavaScript知識點總結(五)之Javascript中兩個等于號(==)和三個等于號(===)的區(qū)別
這篇文章主要介紹了JavaScript知識點總結(五)之Javascript中兩個等于號(==)和三個等于號(===)的區(qū)別的相關資料,需要的朋友可以參考下2016-05-05
javascript實現(xiàn)動態(tài)改變層大小的方法
這篇文章主要介紹了javascript實現(xiàn)動態(tài)改變層大小的方法,涉及javascript操作頁面屬性的相關技巧,需要的朋友可以參考下2015-05-05

