優(yōu)雅的在React項(xiàng)目中使用Redux的方法
或許你當(dāng)前的項(xiàng)目還沒有到應(yīng)用Redux的程度,但提前了解一下也沒有壞處
首先我們會(huì)用到哪些框架和工具呢?
React
UI框架
Redux
狀態(tài)管理工具,與React沒有任何關(guān)系,其他UI框架也可以使用Redux
react-redux
React插件,作用:方便在React項(xiàng)目中使用Redux
react-thunk
中間件,作用:支持異步action
|--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)值
// 這里我們列舉兩個(gè)示例
// 同步數(shù)據(jù):pageTitle
// 異步數(shù)據(jù):infoList(將來用異步接口獲?。?
export default {
pageTitle: '首頁(yè)',
infoList: []
}
第2步:創(chuàng)建reducer,它就是將來真正要用到的數(shù)據(jù),我們將其統(tǒng)一放置在reducers.js文件
// reducers.js
// 工具函數(shù),用于組織多個(gè)reducer,并返回reducer集合
import { combineReducers } from 'redux'
// 默認(rèn)值
import defaultState from './state.js'
// 一個(gè)reducer就是一個(gè)函數(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,但是還沒有對(duì)應(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)異步請(qǐng)求
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一個(gè)action時(shí),需要給dispatch函數(shù)傳入action對(duì)象;但如果我們使用了這個(gè)中間件,那么就可以傳入一個(gè)函數(shù),這個(gè)函數(shù)接收兩個(gè)參數(shù):dispatch和getState。這個(gè)dispatch可以在將來的異步請(qǐng)求完成后使用,對(duì)于異步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
// App.js
import React from 'react'
import ReactDOM from 'react-dom'
// 引入組件
import TestComponent from './components/Test.jsx'
// Provider是react-redux兩個(gè)核心工具之一,作用:將store傳遞到每個(gè)項(xiàng)目中的組件中
// 第二個(gè)工具是connect,稍后會(huì)作介紹
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傳遞給組件,并返回新的組件,組件在該過程中不會(huì)受到影響
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) {
// 如果不懂這里的邏輯可查看前面對(duì)redux-thunk的介紹
dispatch(setPageTitle(data))
// 執(zhí)行setPageTitle會(huì)返回一個(gè)函數(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ù)源
整個(gè)應(yīng)用的 state 被儲(chǔ)存在一棵 object tree 中,并且這個(gè) object tree 只存在于唯一一個(gè) store 中
State 是只讀的
唯一改變 state 的方法就是觸發(fā) action,action 是一個(gè)用于描述已發(fā)生事件的普通對(duì)象
使用純函數(shù)來執(zhí)行修改
為了描述 action 如何改變 state tree ,你需要編寫 reducers
結(jié)語(yǔ)
感謝您的觀看,以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React-Native做一個(gè)文本輸入框組件的實(shí)現(xiàn)代碼
這篇文章主要介紹了React-Native做一個(gè)文本輸入框組件的實(shí)現(xiàn)代碼,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-08-08
react native基于FlatList下拉刷新上拉加載實(shí)現(xiàn)代碼示例
這篇文章主要介紹了react native基于FlatList下拉刷新上拉加載實(shí)現(xiàn)代碼示例2018-09-09
詳解在React項(xiàng)目中安裝并使用Less(用法總結(jié))
這篇文章主要介紹了詳解在React項(xiàng)目中安裝并使用Less(用法總結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
React高級(jí)指引之Refs and the DOM使用時(shí)機(jī)詳解
在典型的React數(shù)據(jù)流中,props是父組件與子組件交互的唯一方式。要修改一個(gè)子組件,你需要使用新的props來重新渲染它。但是,在某些情況下,你需要在典型數(shù)據(jù)流之外強(qiáng)制修改子組件2023-02-02
React實(shí)現(xiàn)模糊搜索和關(guān)鍵字高亮的示例代碼
這篇文章主要為大家詳細(xì)介紹了React如何實(shí)現(xiàn)模糊搜索和關(guān)鍵字高亮的效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11
Create?react?app修改webapck配置導(dǎo)入文件alias
這篇文章主要為大家介紹了Create?react?app修改webapck配置導(dǎo)入文件alias,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12

