如何优雅地在React项目中使用Redux

更新日期: 2017-12-28阅读: 3.1k标签: redux

前言

或许你当前的项目还没有到应用Redux的程度,但提前了解一下也没有坏处,本文不会安利大家使用Redux


概念

首先我们会用到哪些框架工具呢?

react

UI框架

Redux

状态管理工具,与React没有任何关系,其他UI框架也可以使用Redux

react-redux

React插件,作用:方便在React项目中使用Redux

react-thunk

中间件,作用:支持异步action


目录结构

Tips:与Redux无关的目录已省略

|--src
    |-- store                 Redux目录
        |-- actions.js
        |-- index.js
        |-- reducers.js
        |-- state.js
    |-- components      组件目录
        |-- Test.jsx
    |-- App.js               项目入口
    


准备工作

第1步:提供默认值,既然用Redux来管理数据,那么数据就一定要有默认值,所以我们将state的默认值统一放置在state.js文件

// state.js

// 声明默认值
// 这里我们列举两个示例
// 同步数据:pageTitle
// 异步数据:infoList(将来用异步接口获取)
export default {
    pageTitle: '首页',
    infoList: []
}

第2步:创建reducer,它就是将来真正要用到的数据,我们将其统一放置在reducers.js文件

// reducers.js

// 工具函数,用于组织多个reducer,并返回reducer集合
import { combineReducers } from 'redux'
// 默认值
import defaultState from './state.js'

// 一个reducer就是一个函数
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
  }
}

// 导出所有reducer
export default combineReducers({
    pageTitle,
    infoList
})

第3步:创建action,现在我们已经创建了reducer,但是还没有对应的action来操作它们,所以接下来就来编写action

// actions.js

// action也是函数
export function setPageTitle (data) {
  return (dispatch, getState) => {
    dispatch({ type: 'SET_PAGE_TITLE', data: data })
  }
}

export function setInfoList (data) {
  return (dispatch, getState) => {
    // 使用fetch实现异步请求
    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 })
        }
    })
  }
}

最后一步:创建store实例

// index.js

// applyMiddleware: redux通过该函数来使用中间件
// createStore: 用于创建store实例
import { applyMiddleware, createStore } from 'redux'

// 中间件,作用:如果不使用该中间件,当我们dispatch一个action时,需要给dispatch函数传入action对象;但如果我们使用了这个中间件,那么就可以传入一个函数,这个函数接收两个参数:dispatch和getState。这个dispatch可以在将来的异步请求完成后使用,对于异步action很有用
import thunk from 'redux-thunk'

// 引入reducer
import reducers from './reducers.js'

// 创建store实例
let store = createStore(
  reducers,
  applyMiddleware(thunk)
)

export default store

至此,我们已经完成了所有使用Redux的准备工作,接下来就在React组件中使用Redux


开始使用

首先,我们来编写应用的入口文件APP.js


import React from 'react'
import Reactdom from 'react-dom'

// 引入组件
import TestComponent from './components/Test.jsx'

// Provider是react-redux两个核心工具之一,作用:将store传递到每个项目中的组件中
// 第二个工具是connect,稍后会作介绍
import { Provider } from 'react-redux'
// 引入创建好的store实例
import store from '@/store/index.js'

// 渲染DOM
ReactDOM.render (
  (
    <div>
        {/* 将store作为prop传入,即可使应用中的所有组件使用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
    
    // 触发setPageTitle action
    setPageTitle('新的标题')
    
    // 触发setInfoList action
    setInfoList()
  }

  render () {
    // 从props中解构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))
        // 执行setPageTitle会返回一个函数
        // 这正是redux-thunk的所用之处:异步action
        // 上行代码相当于
        /*dispatch((dispatch, getState) => {
            dispatch({ type: 'SET_PAGE_TITLE', data: data })
        )*/
    },
    setInfoList (data) {
        dispatch(setInfoList(data))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Test)


Redux三大原则

  • 单一数据源

整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中

  • State 是只读的

唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象

  • 使用纯函数来执行修改

为了描述 action 如何改变 state tree ,你需要编写 reducers


结语

以上就是在React项目中使用Redux的简单示例,文中代码可能会有编写错误,欢迎指正,同事希望本文对大家有所帮助


参考

原文出处:如何优雅地在React项目中使用Redux

链接: https://www.fly63.com/article/detial/289

React项目实战:react-redux-router基本原理

React项目实战:react-redux-router基本原理,Redux 的 React 绑定库包含了 容器组件和展示组件相分离 的开发思想。明智的做法是只在最顶层组件(如路由操作)里使用 Redux。其余内部组件仅仅是展示性的,所有数据都通过 props 传入。

react关于 Redux与flux的比较学习

flux四大元素:Dispatcher:根据注册派发动作(action),Store: 存储数据,处理数据,Action:用于驱动Dispatcher,View: 用户界面视图。flux的目的:纠正MVC框架的无法禁绝view与model通信的缺点。Redux基本原则:继承Flux基本原则:单向数据流

从 源码 谈谈 redux compose

compose,英文意思 组成,构成。它的作用也是通过一系列的骚操作,实现任意的、多种的、不同的功能模块的组合,用来加强组件。很容易实现功能的组合拼装、代码复用;可以根据需要组合不同的功能;

Redux与它的中间件:redux-thunk,redux-actions,redux-promise,redux-sage

这里要讲的就是一个Redux在React中的应用问题,讲一讲Redux,react-redux,redux-thunk,redux-actions,redux-promise,redux-sage这些包的作用和他们解决的问题。

redux中间件的原理_深入理解 Redux 中间件

最近几天对 redux 的中间件进行了一番梳理,又看了 redux-saga 的文档,和 redux-thunk 和 redux-promise 的源码,结合前段时间看的redux的源码的一些思考,感觉对 redux 中间件的有了更加深刻的认识,因此总结一下

react-redux 的使用

类似于 Vue,React 中组件之间的状态管理 第三方包为:react-redux。react-redux 其实是 Redux的官方React绑定库,它能够使你的React组件从Redux store中读取数据,并且向store分发actions以更新数据。

如何使用useReducer Hook?

看到“reducer”这个词,容易让人联想到Redux,但是在本文中,不必先理解Redux才能阅读这篇文章。咱们将一起讨论“reducer”实际上是什么,以及如何利用useReducer来管理组件中的复杂状态,以及这个新钩子对Redux意味着什么?

带着问题看React-Redux源码

我在读React-Redux源码的过程中,很自然的要去网上找一些参考文章,但发现这些文章基本都没有讲的很透彻,很多时候就是平铺直叙把API挨个讲一下,而且只讲某一行代码是做什么的,却没有结合应用场景和用法解释清楚为什么这么做。

React Hooks 是不能替代 Redux 的

我的许多同事最近通过各种方式问同一类问题:“如果我们开始用 hook 后,那还有必要用 Redux 吗?”“React hook 不是让 Redux 过时了吗?那只用 Hooks 就可以做 Redux 所有能做的事了吧?”

redux和react-redux

redux是react的状态管理工具,却不仅仅只是为了react而生的,所以在使用中会存在痛点。而react-redux是专门为了react定制,目的是为了解决redux的痛点,起到了补充的作用。flux无非就是一个常见的event dispatcher

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!