尧图精选

Redux实战:轻松实现组件状态共享与同步

🕒 发布时间:2026/10/2 16:07:58 📁 来源:尧图网络
一、简介redux是一个专门用于做状态管理的JS库它可以用在React、Angular、Vue等项目中但基本与React配合使用作用集中式管理React应用中多个组件共享的状态什么情况下需要使用Redux1、某个组件的状态需要让其他组件可以随时拿到共享2、一个组件需要改变另一个组件的状态通信3、总体规则能不用就不用如果不用比较吃力才考虑使用二、React的工作原理三、Redux的三个核心概念1、action动作的对象包含2个属性* type标识的属性值为字符串唯一必要属性* data数据属性值类型任意可选属性例{ typeADD_STUDENT,data{ nametom,age18 } }2、reducer用于初始化状态加工状态加工时根据旧的state和action产生新的state的纯函数3、store将state、action、reducer联系在一起的对象1) 如何得到对象import { createStore } from redux import reducer from ./reducers const store createStore(reducer)2) 此对象的功能getState()得到statedispatch(action)分发action触发reducer调用产生新的statesubscribe(listener)注册监听当产生了新的state时自动调用四、求和案例1、纯react版import { React{ Component } } from react export default class Count extends Component { state { count:0 } increment () { const { value } this.selectNumber const { count } this.state this.setState({ count : count value*1 }) } decrement () { const { value } this.selectNumber const { count } this.state this.setState({ count : count - value*1 }) } incrementIfOdd () { const { value } this.selectNumber const { count } this.state if(count % 2 ! 0){ this.setState({ count : count value*1 }) } } incrementAsync () { const { value } this.selectNumber const { count } this.state setTimeout((){ this.setState({ count : count value*1 }) },1000) } render( div h1当前求和为{ this.state.count }/h1 select ref{ c this.selectNumber c } option value11/option option value22/option option value33/option /select button onClick { this.increment }/button button onClick { this.decrement }-/button button onClick { this.incrementIfOdd }当前求和为奇数再加/button button onClick { this.incrementAsync }异步加/button /div ) }2、Store的简单使用在src文件夹中创建redux文件夹在redux文件夹中创建store.js和count_reducer.js文件store.js//该文件专门用于暴露一个store对象整个应用只有一个store对象 //引入createStore专门用于创建redux中最为核心的store对象 import { createStore } from redux //引入为Count组件服务的reducer import countReducer from ./count_reducer //暴露store export default createStore(countReducer)count_reducer.js//该文件是用于一个为Count组件服务的reducerreducer的本质就是一个函数 //reducer函数会接收到两个参数分别为之前的参数(preState),动作对象(action) export default function countReducer(preState,action){ if(preState undefined) preState 0 //默认状态下的值 //action对象中获取type、data const { typedata } action //根据type决定如何加工数据 switch ( type ) { case increment: //如果是加 return preState data case decrement: //如果是减 return preState - data default return preState } }改造Count组件import { React{ Component } } from react //引入store用于获取redux中保存状态 import store from ./redux/store export default class Count extends Component { state { car:0 } componentDidMount(){ //检测redux中状态的变化只要变化就会调用render store.subscribe((){ this.setState({}) }) } increment () { const { value } this.selectNumber //const { count } this.state //this.setState({ count : count value*1 }) store.dispatch({ type:increment,data:value*1 }) } decrement () { const { value } this.selectNumber //const { count } this.state //this.setState({ count : count - value*1 }) store.dispatch({ type:decrement,data:value*1 }) } incrementIfOdd () { const { value } this.selectNumber const { count } store.getState() if(count % 2 ! 0){ //this.setState({ count : count value*1 }) store.dispatch({ type:increment,data:value*1 }) } } incrementAsync () { const { value } this.selectNumber setTimeout((){ //this.setState({ count : count value*1 }) store.dispatch({ type:decrement,data:value*1 }) },1000) } render( div h1当前求和为{ store.getState() }/h1 select ref{ c this.selectNumber c } option value11/option option value22/option option value33/option /select button onClick { this.increment }/button button onClick { this.decrement }-/button button onClick { this.incrementIfOdd }当前求和为奇数再加/button button onClick { this.incrementAsync }异步加/button /div ) }componentDidMount(){//检测redux中状态的变化只要变化就会调用renderstore.subscribe((){this.setState({})})}在 React 类组件中于componentDidMount生命周期内调用store.subscribe并执行this.setState({})其核心目的是‌建立 Redux Store 状态变化与 React 组件视图更新之间的自动响应机制‌。1. 解决“数据流断层”问题Redux 和 React 是两个独立的库‌Redux‌ 负责管理全局状态State当状态改变时它只会通知通过subscribe注册的监听器。‌React‌ 负责渲染 UI只有当组件的state或props发生变化时才会触发render重新渲染。默认情况下Redux 状态更新‌不会‌自动触发 React 组件的重新渲染。如果不进行订阅即使 Store 中的数据变了组件依然显示旧数据。通过store.subscribe我们让组件“监听”Store 的变化通过this.setState({})我们强制 React 重新执行render从而从 Store 中获取最新的数据并更新界面。2. 为什么选择componentDidMount‌确保组件已挂载‌componentDidMount在组件第一次渲染并完成 DOM挂载后执行。此时组件实例已经存在可以安全地访问this和this.setState。‌避免重复订阅‌如果在render或constructor中订阅可能会导致每次渲染都添加一个新的监听器造成内存泄漏和性能问题。componentDidMount只执行一次适合初始化订阅关系。检测redux中状态的变化从而调用render进行刷新数据如果组件过多上述代码也会过多可以在index.js入口文件中写import React from react import ReactDOM from react-dom import App from ./App import store from ./redux/store // ReactDOM.render(App /,document.getElementById(root)) store.subscribe((){ ReactDOM.render(App /,document.getElementById(root)) })
上一篇/下一篇内容由系统自动关联 返回资讯列表 →