标签:redux 入门 reducer 学习 state action Redux store
Redux学习笔记
redux 和react没有必然关系,redux可以应用于各种框架,包括jquery,甚至js都可以使用redux,只不过redux和react更加搭配。redux也推出了专门应用于react的react-redux。
1. Redux概述
- Redux就是一个JavaScript容器,用来进行全局的状态管理
- Redux三大核心
- 单一数据源头(所有的state的数据都存储在一个Object Tree中)
- State只读(要想修改只能通过发送action来进行修改)
- 使用纯函数来进行修改(使用纯函数可以提高复用性,reduce就是一个纯函数,用来接收action )
2. Redux组成
- State状态
- DomainState :服务器返回的State
- UI State: 关于当前组件的State
- APP State: 全局State
- Action事件
- 本质就是一个JS对象
- 必须包含type属性
- 只描述了有事情发生,并没有描述如何去更新State
- Reducer
- 本质就是函数
- 响应发送过来的action
- 函数接收两个参数,第一个是初始化state,第二个是发送过来的action
- Store
- 用来吧action和reducer关联到一起的
- 通过createStore 来构建store
- 通过subscribe 来注册监听
- 通过dispatch来发送action
3.Redux 入门案例
数据流转
就是通过store.dispatch 来进行更新store中的数据,然后会按照reducer方法中的处理逻辑来更新store的数据,组件会通过store.subscriber监听来获取更新的数据,可以通过setState等方法来更新数据进而重新更新组件
简单步骤
-
构建action对象,通过创建一个函数,来返回一个对象,返回的action对象需要有type属性,否则会报错。
action.js
export const sendAction = (action)=>{ return{ type: "sendAction", ...action } }
-
构建reducer,用来响应action,然后通过action的type值来进行单独的数据处理并将数据return 给store。
reducer.js
const initState = {value: "这是sate默认值"}; export const reducer = (state = initState, action ) => { console.log("reducer",state,action) switch (action.type) { case "sendAction": return Object.assign({},state,action); default : return state; } }
-
构建store,通过redux中的createRedux来创建store,createStore需要传进 构建的reducer函数,这样就会按照定义的reducer函数的处理逻辑来处理数据。
store.js
import {createStore} from "redux"; import {reducer} from "./reducer";//自定义的reducer函数 export const store = createStore(reducer);
-
利用store.subscriber()来注册监听,接收store更新后的数据。
home/index.js
store.subscribe(() => { console.log("subscribe",store.getState()) })
-
当利用store.dispatch来发送一个action的时候,就能触发监听了,在监听中通过store.getState()就可以拿到更新后的值了。
home/index.jsx
import React, {Component} from 'react'; import {sendAction} from "../action"; import {store} from "../store"; class Home extends Component { constructor(props){ super(props); this.state = { actionValue: "", }; } componentDidMount() { //接收store更新的数据 store.subscribe(() => { console.log("subscribe",store.getState()); this.setState({actionValue: store.getState().value}); }) } // 发送action handleAction = () =>{ const action = sendAction({value:"这是一个action"}); store.dispatch(action); } render() { return ( <div> <button onClick={this.handleAction}>发送一个action</button> <div> <h4>这是action的值: {this.state.actionValue}</h4> </div> </div> ); } } export default Home;
标签:redux,入门,reducer,学习,state,action,Redux,store 来源: https://blog.csdn.net/qq_40600414/article/details/121599837
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。