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在原生的redux中action只能返回对象,但是加上这个中间件就可以返回一个函数并且可以访问其他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分发一个action到reducer并把action函数合并到该组件中的props
链接
Blog_demo 本文redux_demo
结语
关于在react项目中如何使用redux,以及具体写法,我的分层方式这些都在此文中有所展现。但是这只是刚接触时,我的一些思路,还有一些有趣的东西我会在后续中提及(router 与 redux 绑定 ,middleware 的基本原理等)如果各位大佬有更好的思路请在留言告诉我,不胜感激
本文深入探讨了Redux作为JS状态容器,在React项目中的应用。介绍了如何安装与配置Redux,利用Redux-devtools进行调试,以及如何通过React-Redux将Redux状态与React组件相连接。通过实例展示了Redux的三大原则及其实现细节。
160

被折叠的 条评论
为什么被折叠?



