初探React技术栈(二)

571 阅读3分钟

redux

redux是js的状态容器,提供可预测的状态管理,同时可运行于不同的环境并且还有redux-devtools供可视化调试,大型应用下有良好的跨组件通讯与状态管理是必不可少的,那么就在本章中探索redux是如何与react串联,并是如何使用redux

$ npm or cnpm
$ npm install redux react-redux

相信有不少人都比较好奇 为什么我已经有了redux还要再多引入一个react-redux实际上这样是为保证核心功能最大程度上的跨平台复用

首先新建一个文件夹store用来存放redux的配置及相关文件,看一下store中的文件结构

├── actions
│   └── index.js
├── index.js
└── reducers
    └── index.js

2 directories, 3 files

# 其中最外层的index.js是主要的配置文件

在react的入口文件index.js中引入react-redux

示例图片

Provider是react-redux两个核心工具之一,作用:将store传递到项目的组件中,并可以在组件中使用redux

import一般引入文件夹会默认找到该文件夹中的index.js

store.js reudx 主文件

import { applyMiddleware, createStore } from 'redux'

import thunk from 'redux-thunk'

import reducers from './reducers/index'

let store = createStore(
    reducers,
    applyMiddleware(thunk)
)

export default store

redux中以createStore创建store并在其中插入reducers与中间件,redux-thunk是为了增强action在原生的reduxaction只能返回对象,但是加上这个中间件就可以返回一个函数并且可以访问其他action

action

// 测试action
function test (text) {
    return { type: 'test', text: text }
}

export default {
    test
}

reducer

import { combineReducers } from 'redux'

const Initstate = {
    // 初始状态
}
const Common = (state = Initstate, action) => {
    switch (action.type) {
        case 'test':
            return {...state, test: action.text}
        default: 
            return state
    }
}

let reducer = combineReducers({
    Common: Common
})
// 注意combineReducers是用于合并多个reducer 当所用模块不多,协作少时 可以不用

从reducer中我们就可以发现redux的三大原则:

1.单一数据源: 所谓的单一数据源是只有一个Model虽然我们可以定义多个 reducer 但是经过combineReducers 整合发现 所有的 Model 都存在一个大的JSON里面

2.状态是只读: 我们可以发现当我们接收到名为test的变化时;并不是修改 Initstate 而是?> 直接返回state相当于只是读取这个默认状态并与action中返回的状态整合

3.状态修改均有纯函数完成:可以发现 common这个函数实用switch接收到一定的action.type 就会返回相应的属猪

与react组件相结合

以App.jsx示例

import React, { Component } from 'react'
import { connect } from 'react-redux'
import Action from ‘./../store/actions/index’

class App extends Component {
    test () {
        this.props.test(‘test’)
        // 测试数据
    }
    render () {
        return (
            <div>
                { this.props.test } {/*测试数据*/}
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        test: state.Common.test
    }
}

const mapDispatchToProps = (dispatch, ownProps)  => {
    return {
        test: (data) => dispatch(Action.test(data))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

mapStateToProps: 这个函数的主要主要作用在与把modal中的状态与该组件的props进行融合以至于组件可以直接通过this.props.test访问到modal中的状态

mapDispatchToProps: 这个函数的主要作用是把action中的函数通过dispatch分发一个actionreducer并把action函数合并到该组件中的props

链接

Blog_demo 本文redux_demo

我的博客

redux

结语

关于在react项目中如何使用redux,以及具体写法,我的分层方式这些都在此文中有所展现。但是这只是刚接触时,我的一些思路,还有一些有趣的东西我会在后续中提及(router 与 redux 绑定 ,middleware 的基本原理等)如果各位大佬有更好的思路请在留言告诉我,不胜感激