欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

優(yōu)雅的在React項(xiàng)目中使用Redux的方法

 更新時(shí)間:2018年11月10日 14:31:01   作者:前端愛好者  
這篇文章主要介紹了優(yōu)雅的在React項(xiàng)目中使用Redux的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

或許你當(dāng)前的項(xiàng)目還沒有到應(yīng)用Redux的程度,但提前了解一下也沒有壞處

首先我們會用到哪些框架和工具呢?

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: '首頁',
  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,但是還沒有對應(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一個(gè)action時(shí),需要給dispatch函數(shù)傳入action對象;但如果我們使用了這個(gè)中間件,那么就可以傳入一個(gè)函數(shù),這個(gè)函數(shù)接收兩個(gè)參數(shù):dispatch和getState。這個(gè)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

// 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,稍后會作介紹
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會返回一個(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 被儲存在一棵 object tree 中,并且這個(gè) object tree 只存在于唯一一個(gè) store 中

State 是只讀的
唯一改變 state 的方法就是觸發(fā) action,action 是一個(gè)用于描述已發(fā)生事件的普通對象

使用純函數(shù)來執(zhí)行修改
為了描述 action 如何改變 state tree ,你需要編寫 reducers

結(jié)語

感謝您的觀看,以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論