首页 >> 大全

Redux和React-redux(详解和案例)

2024-01-09 大全 42 作者:考证青年

Redux

源码地址:

是什么

redux是一个专门用于做状态管理的JS库(不是react插件库)。

它可以用在react, , vue等项目中, 但基本与react配合使用。

作用: 集中式管理react应用中多个组件共享的状态。什么

什么时候使用

某个组件的状态,需要让其他组件可以随时拿到(共享)。

一个组件需要改变另一个组件的状态(通信)。

总体原则:能不用就不用, 如果不用比较吃力才考虑使用。

核心概念

就是把我们的行为包装成一个对象。自己写也可以。其也可以是个函数(异步)

动作的对象

包含2个属性

例子:{ type: ‘’,data:{name: ‘tom’,age:18} }

初始化时type:@@+随机字符的形式,date为

具体执行我们指定行为的人

用于初始化状态、加工状态。

加工时,根据旧的state和, 产生新的state的纯函数

初始化的时候为

store

是总控中心,分配任务给,拿到做的结果

将state、、联系在一起的对象

如何得到此对象?

{} from ‘redux’

from ‘./’

const store = ()

此对象的功能?

(): 得到state

(): 分发, 触发调用, 产生新的state

3)(): 注册监听, 当产生了新的state时, 自动调用

react实现计算器

export default class Count extends Component {state = {count:0}//加法increment = ()=>{const {value} = this.selectNumberconst {count} = this.statethis.setState({count:count+value*1})}//减法decrement = ()=>{const {value} = this.selectNumberconst {count} = this.statethis.setState({count:count-value*1})}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberconst {count} = this.stateif(count % 2 !== 0){this.setState({count:count+value*1})}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberconst {count} = this.statesetTimeout(()=>{this.setState({count:count+value*1})},500)}render() {return (<div><h1>当前求和为:{this.state.count}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}

_reactredux原理_reactnative案例

redux实现计算器

(1).去除Count组件自身的状态

(2).src下建立:

-redux

-store.js

-.js

  (3).store.js:1).引入redux中的createStore函数,创建一个store2).createStore调用时要传入一个为其服务的reducer3).记得暴露store对象(4).count_reducer.js:1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态2).reducer有两个作用:初始化状态,加工状态3).reducer被第一次调用时,是store自动触发的,传递的preState是undefined,传递的action是:{type:'@@REDUX/INIT_a.2.b.4}(5).在index.js中监测store中状态的改变,一旦发生改变重新渲染备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写。

创建干活的人

/* 1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from './constant'const initState = 0 //初始化状态
export default function countReducer(preState=initState,action){// console.log(preState);//从action对象中获取:type、dataconst {type,data} = action//根据type决定如何加工数据switch (type) {case INCREMENT: //如果是加return preState + datacase DECREMENT: //若果是减return preState - datadefault:return preState}
}

创建老板store

/* 该文件专门用于暴露一个store对象,整个应用只有一个store对象
*///引入createStore,专门用于创建redux中最为核心的store对象
import {createStore} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//暴露store
export default createStore(countReducer)

创建行为对象

/* 该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})

创建行为定义

/* 该模块是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

计算器逻辑

export default class Count extends Component {state = {carName:'奔驰c63'}/* componentDidMount(){//检测redux中状态的变化,只要变化,就调用renderstore.subscribe(()=>{this.setState({})})} *///加法increment = ()=>{const {value} = this.selectNumberstore.dispatch(createIncrementAction(value*1))}//减法decrement = ()=>{const {value} = this.selectNumberstore.dispatch(createDecrementAction(value*1))}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberconst count = store.getState()if(count % 2 !== 0){store.dispatch(createIncrementAction(value*1))}}//异步加incrementAsync = ()=>{const {value} = this.selectNumbersetTimeout(()=>{store.dispatch(createIncrementAction(value*1))},500)}render() {return (<div><h1>当前求和为:{store.getState()}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}

index.js监控store变化

ReactDOM.render(<App/>,document.getElementById('root'))
//监控redux的状态变化,只要一变化就调用render
store.subscribe(()=>{ReactDOM.render(<App/>,document.getElementById('root'))
})

异步

store

/* 该文件专门用于暴露一个store对象,整个应用只有一个store对象
*///引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//暴露store
export default createStore(countReducer,applyMiddleware(thunk))

/* 该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'//同步action,就是指action的值为Object类型的一般对象
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const createIncrementAsyncAction = (data,time) => {return (dispatch)=>{setTimeout(()=>{dispatch(createIncrementAction(data))},time)}
}

之前那是在具体的组件中使用定时器,现在直接把定时任务放在中,传入data和time作为参数。

//异步加incrementAsync = ()=>{const {value} = this.selectNumber// setTimeout(()=>{store.dispatch(createIncrementAsyncAction(value*1,500))// },500)}

store调用方法,返回函数

(dispatch)=>{setTimeout(()=>{dispatch(createIncrementAction(data))},time)}

执行定时函数

React-redux

改写计算器

(1).明确两个概念:

1).UI组件:不能使用任何redux的api,只负责页面的呈现、交互等。

2).容器组件:负责和redux通信,将结果交给UI组件。

(2).如何创建一个容器组件————靠react-redux 的 函数

(,)(UI组件)

-:映射状态,返回值是一个对象

-:映射操作状态的方法,返回值是一个对象

(3).备注1:容器组件中的store是靠props传进去的,而不是在容器组件中直接引入

(4).备注2:,也可以是一个对象

相比之前不用React-redux,除了上述还有如下优点:

1.不需要手动监听Store了,react-redux框架自动帮我们监听

2.不需要在每个容器组件提供store,可以在最上层index.js

// 给所有的容器组件传入了store
ReactDOM.render(<Provider store={store}><App/></Provider>,document.getElementById('root')
)

APP组件

export default class App extends Component {render() {return (<div>{/* 给容器组件传递store */}<Count store={store} /></div>)}
}

容器组件

//引入Count的UI组件
import CountUI from '../../components/Count'
//引入action
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction
} from '../../redux/count_action'//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'/* 1.mapStateToProps函数返回的是一个对象;2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value3.mapStateToProps用于传递状态
*/
function mapStateToProps(state){return {count:state}
}/* 1.mapDispatchToProps函数返回的是一个对象;2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch){return {jia:number => dispatch(createIncrementAction(number)),jian:number => dispatch(createDecrementAction(number)),jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),}
}//使用connect()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

UI组件

export default class Count extends Component {state = {carName:'奔驰c63'}//加法increment = ()=>{const {value} = this.selectNumberthis.props.jia(value*1)}//减法decrement = ()=>{const {value} = this.selectNumberthis.props.jian(value*1)}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberif(this.props.count % 2 !== 0){this.props.jia(value*1)}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberthis.props.jiaAsync(value*1,500)}render() {//console.log('UI组件接收到的props是',this.props);return (<div><h1>当前求和为:{this.props.count}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}

进一步精简

(1).容器组件和UI组件整合一个文件

(2).无需自己给容器组件传递store,给包裹一个即可。

(3).使用了react-redux后也不用再自己检测redux中状态的改变了,容器组件可以自动完成这个工作。

(4).也可以简单的写成一个对象

(5).一个组件要和redux“打交道”要经过哪几步?

(1).定义好UI组件—不暴露

(2).引入生成一个容器组件,并暴露,写法如下:

(

state => ({key:value}), //映射状态

{key:} //映射操作状态的方法

)(UI组件)

(3).在UI组件中通过this.props.读取和操作状态

//index.js
ReactDOM.render(<Provider store={store}><App/></Provider>,document.getElementById('root')
)

容器组件和UI组件融合

//定义UI组件
class Count extends Component {state = {carName:'奔驰c63'}//加法increment = ()=>{const {value} = this.selectNumberthis.props.jia(value*1)}//减法decrement = ()=>{const {value} = this.selectNumberthis.props.jian(value*1)}//奇数再加incrementIfOdd = ()=>{const {value} = this.selectNumberif(this.props.count % 2 !== 0){this.props.jia(value*1)}}//异步加incrementAsync = ()=>{const {value} = this.selectNumberthis.props.jiaAsync(value*1,500)}render() {//console.log('UI组件接收到的props是',this.props);return (<div><h1>当前求和为:{this.props.count}</h1><select ref={c => this.selectNumber = c}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>&nbsp;<button onClick={this.increment}>+</button>&nbsp;<button onClick={this.decrement}>-</button>&nbsp;<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;<button onClick={this.incrementAsync}>异步加</button>&nbsp;</div>)}
}//使用connect()()创建并暴露一个Count的容器组件
export default connect(state => ({count:state}),//mapDispatchToProps的一般写法/* dispatch => ({jia:number => dispatch(createIncrementAction(number)),jian:number => dispatch(createDecrementAction(number)),jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),}) *///mapDispatchToProps的简写{jia:createIncrementAction,jian:createDecrementAction,jiaAsync:createIncrementAsyncAction,}
)(Count)

两个容组件交互数据案例

增加一个组件,只要在store存储的状态,count组件和组件可以访问里面的数据

坑:

一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)

必须遵守以下一些约束

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了