redux
是js的状态容器,提供可预测的状态管理,同时可运行于不一样的环境而且还有redux-devtools
供可视化调试,大型应用下有良好的跨组件通信与状态管理是必不可少的,那么就在本章中探索redux
是如何与react
串联,并是如何使用redux
javascript
$ npm or cnpm $ npm install redux react-redux
相信有很多人都比较好奇 为何我已经有了redux
还要再多引入一个react-redux
实际上这样是为保证核心功能最大程度上的跨平台复用
首先新建一个文件夹store
用来存放redux的配置及相关文件,看一下store
中的文件结构java
. ├── actions │ └── index.js ├── index.js └── reducers └── index.js 2 directories, 3 files # 其中最外层的index.js是主要的配置文件
在react的入口文件index.js
中引入react-redux
react
Provider是react-redux两个核心工具之一,做用:将store传递到项目的组件中,并能够在组件中使用redux
import
通常引入文件夹会默认找到该文件夹中的index.js
git
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
只能返回对象,可是加上这个中间件就能够返回一个函数而且能够访问其余actiongithub
// 测试action function test (text) { return { type: 'test', text: text } } export default { test }
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里面npm2.
状态是只读
: 咱们能够发现当咱们接收到名为test
的变化时;并非修改Initstate
而是?> 直接返回state
至关于只是读取这个默认状态并与action
中返回的状态整合 redux3.
状态修改均有纯函数完成
:能够发现common
这个函数实用switch
接收到必定的action.type
就会返回相应的属猪bash
以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
app
Blog_demo 本文redux_demo ide
关于在react项目中如何使用redux,以及具体写法,个人分层方式这些都在此文中有所展示。可是这只是刚接触时,个人一些思路,还有一些有趣的东西我会在后续中说起(router 与 redux 绑定 ,middleware 的基本原理等)若是各位大佬有更好的思路请在留言告诉我,不胜感激