react redux 状态管理

1.store

store是一个状态管理容器,它通过createStore创建,createStore接收initialState和reducer两个参数。它暴露了4个api分别是:

getState()
dispatch(action)
subscribe(listener)
replaceReducer

前三个是比较常用的api,之后我们会来模拟实现一个createStore这个函数。

2.action

在redux思想中view的变化由action发出通知,action是一个包含type的简单对象,在redux思想中改变state的唯一方法就是触发action

3.dispatch

dispatch用来处理action,并传递给reducer,继而更新应用状态

4.reducer

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
在React中使用redux的数据流向如图所示:

在这里插入图片描述

结构如下

在这里插入图片描述
store.js

import { createStore } from 'redux'
import { rootReducer } from './reducer/index';

const store = createStore(rootReducer)

export default store;

action/index.js

/**
 * action 构建函数
 */
export const sendAction = (obj) => {
  // console.log(obj);
  // 需要返回一个action对象,该action对象需要包括type等属性
  return {
    type: 'send-action',
    value: '这是一个action'
  }
}

redecer/index.js

/**
 * 该文件是创建reducer函数,专门用于处理发送过来的action
 */

const initState = {
  value: '默认值'
}
// 函数需要传递两个参数:state,action
const rootReducer = (state = initState, action) => {
  // 根据aciton中的type字段判断是否为发送过来的action,如果是则返回一个新的state
  switch (action.type) {
    case 'send-action':
      return Object.assign({}, state, action)
    default:
      return state
  }
}
export {
  rootReducer
};

项目中使用
…未完待续

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Redux是一个用于在React应用中管理状态的库。它结合了ReactRedux,提供了一种可预测的状态管理解决方案。在React Redux中,我们使用Provider组件将Redux的store传递给整个应用程序,以便在应用程序的任何地方都可以访问到Redux状态。\[1\]\[3\] 在React Redux中,我们可以使用connect函数将组件连接到Redux的store,并将store中的状态映射到组件的props上。这样,组件就可以通过props访问和更新Redux状态。同时,我们还可以使用dispatch函数来触发Redux中的action,从而更新状态。\[2\] 通过React Redux,我们可以更方便地管理React应用的状态,使得应用的状态变化更加可控和可预测。同时,React Redux还提供了一些中间件,如Redux-thunk,可以帮助我们处理异步操作,使得应用的状态管理更加灵活和强大。\[2\] 总之,React Redux是一个强大的状态管理库,可以帮助我们更好地管理React应用的状态,并提供了一些工具和中间件来简化状态管理的过程。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [React中的Redux](https://blog.csdn.net/yrqlyq/article/details/119118182)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值