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.js2 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
在原生的redux
中action
只能返回对象,但是加上这个中间件就可以返回一个函数并且可以访问其他action
action
// 测试actionfunction 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
分发一个action
到reducer
并把action
函数合并到该组件中的props
链接
Blog_demo 本文redux_demo
我的博客
redux
结语
关于在react项目中如何使用redux,以及具体写法,我的分层方式这些都在此文中有所展现。但是这只是刚接触时,我的一些思路,还有一些有趣的东西我会在后续中提及(router 与 redux 绑定 ,middleware 的基本原理等)如果各位大佬有更好的思路请在留言告诉我,不胜感激