前言
或許你當(dāng)前的項(xiàng)目還沒有到應(yīng)用Redux的程度毡泻,但提前了解一下也沒有壞處,本文不會安利大家使用Redux
概念
首先我們會用到哪些框架和工具呢?
React
UI框架
Redux
狀態(tài)管理工具,與React沒有任何關(guān)系纵菌,其他UI框架也可以使用Redux
react-redux
React插件,作用:方便在React項(xiàng)目中使用Redux
react-thunk
中間件休涤,作用:支持異步action
目錄結(jié)構(gòu)
Tips:與Redux無關(guān)的目錄已省略
|--src
|-- store Redux目錄
|-- actions.js
|-- index.js
|-- reducers.js
|-- state.js
|-- components 組件目錄
|-- Test.jsx
|-- App.js 項(xiàng)目入口
準(zhǔn)備工作
第1步:提供默認(rèn)值咱圆,既然用Redux來管理數(shù)據(jù)盏浇,那么數(shù)據(jù)就一定要有默認(rèn)值窟社,所以我們將state的默認(rèn)值統(tǒng)一放置在state.js文件
// state.js
// 聲明默認(rèn)值
// 這里我們列舉兩個示例
// 同步數(shù)據(jù):pageTitle
// 異步數(shù)據(jù):infoList(將來用異步接口獲取)
export default {
pageTitle: '首頁',
infoList: []
}
第2步:創(chuàng)建reducer这弧,它就是將來真正要用到的數(shù)據(jù)捷凄,我們將其統(tǒng)一放置在reducers.js文件
// reducers.js
// 工具函數(shù)忱详,用于組織多個reducer,并返回reducer集合
import { combineReducers } from 'redux'
// 默認(rèn)值
import defaultState from './state.js'
// 一個reducer就是一個函數(shù)
function pageTitle (state = defaultState.pageTitle, action) {
// 不同的action有不同的處理邏輯
switch (action.type) {
case 'SET_PAGE_TITLE':
return action.data
default:
return state
}
}
function infoList (state = defaultState.infoList, action) {
switch (action.type) {
case 'SET_INFO_LIST':
return action.data
default:
return state
}
}
// 導(dǎo)出所有reducer
export default combineReducers({
pageTitle,
infoList
})
第3步:創(chuàng)建action纵势,現(xiàn)在我們已經(jīng)創(chuàng)建了reducer踱阿,但是還沒有對應(yīng)的action來操作它們,所以接下來就來編寫action
// actions.js
// action也是函數(shù)
export function setPageTitle (data) {
return (dispatch, getState) => {
dispatch({ type: 'SET_PAGE_TITLE', data: data })
}
}
export function setInfoList (data) {
return (dispatch, getState) => {
// 使用fetch實(shí)現(xiàn)異步請求
window.fetch('/api/getInfoList', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
return res.json()
}).then(data => {
let { code, data } = data
if (code === 0) {
dispatch({ type: 'SET_INFO_LIST', data: data })
}
})
}
}
最后一步:創(chuàng)建store實(shí)例
// index.js
// applyMiddleware: redux通過該函數(shù)來使用中間件
// createStore: 用于創(chuàng)建store實(shí)例
import { applyMiddleware, createStore } from 'redux'
// 中間件钦铁,作用:如果不使用該中間件,當(dāng)我們dispatch一個action時才漆,需要給dispatch函數(shù)傳入action對象牛曹;但如果我們使用了這個中間件,那么就可以傳入一個函數(shù)醇滥,這個函數(shù)接收兩個參數(shù):dispatch和getState黎比。這個dispatch可以在將來的異步請求完成后使用超营,對于異步action很有用
import thunk from 'redux-thunk'
// 引入reducer
import reducers from './reducers.js'
// 創(chuàng)建store實(shí)例
let store = createStore(
reducers,
applyMiddleware(thunk)
)
export default store
至此,我們已經(jīng)完成了所有使用Redux的準(zhǔn)備工作阅虫,接下來就在React組件中使用Redux
開始使用
首先演闭,我們來編寫應(yīng)用的入口文件APP.js
import React from 'react'
import ReactDOM from 'react-dom'
// 引入組件
import TestComponent from './components/Test.jsx'
// Provider是react-redux兩個核心工具之一,作用:將store傳遞到每個項(xiàng)目中的組件中
// 第二個工具是connect颓帝,稍后會作介紹
import { Provider } from 'react-redux'
// 引入創(chuàng)建好的store實(shí)例
import store from '@/store/index.js'
// 渲染DOM
ReactDOM.render (
(
<div>
{/* 將store作為prop傳入米碰,即可使應(yīng)用中的所有組件使用store */}
<Provider store = {store}>
<TestComponent />
</Provider>
</div>
),
document.getElementById('root')
)
最后是我們的組件:Test.jsx
// Test.jsx
import React, { Component } from 'react'
// connect方法的作用:將額外的props傳遞給組件,并返回新的組件购城,組件在該過程中不會受到影響
import { connect } from 'react-redux'
// 引入action
import { setPageTitle, setInfoList } from '../store/actions.js'
class Test extends Component {
constructor(props) {
super(props)
}
componentDidMount () {
let { setPageTitle, setInfoList } = this.props
// 觸發(fā)setPageTitle action
setPageTitle('新的標(biāo)題')
// 觸發(fā)setInfoList action
setInfoList()
}
render () {
// 從props中解構(gòu)store
let { pageTitle, infoList } = this.props
// 使用store
return (
<div>
<h1>{pageTitle}</h1>
{
infoList.length > 0 ? (
<ul>
{
infoList.map((item, index) => {
<li>{item.data}</li>
})
}
</ul>
):null
}
</div>
)
}
}
// mapStateToProps:將state映射到組件的props中
const mapStateToProps = (state) => {
return {
pageTitle: state.pageTitle,
infoList: state.infoList
}
}
// mapDispatchToProps:將dispatch映射到組件的props中
const mapDispatchToProps = (dispatch, ownProps) => {
return {
setPageTitle (data) {
// 如果不懂這里的邏輯可查看前面對redux-thunk的介紹
dispatch(setPageTitle(data))
// 執(zhí)行setPageTitle會返回一個函數(shù)
// 這正是redux-thunk的所用之處:異步action
// 上行代碼相當(dāng)于
/*dispatch((dispatch, getState) => {
dispatch({ type: 'SET_PAGE_TITLE', data: data })
)*/
},
setInfoList (data) {
dispatch(setInfoList(data))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)
Redux三大原則
- 單一數(shù)據(jù)源
整個應(yīng)用的 state 被儲存在一棵 object tree 中吕座,并且這個 object tree 只存在于唯一一個 store 中 - State 是只讀的
唯一改變 state 的方法就是觸發(fā) action,action 是一個用于描述已發(fā)生事件的普通對象 - 使用純函數(shù)來執(zhí)行修改
為了描述 action 如何改變 state tree 瘪板,你需要編寫 reducers
結(jié)語
以上就是在React項(xiàng)目中使用Redux的簡單示例吴趴,文中代碼可能會有編寫錯誤,歡迎指正侮攀,同事希望本文對大家有所幫助