Redux中subscribe的作用及說明
更新時間:2023年10月07日 11:30:58 作者:*唔西迪西*
由于redux使用這方面有很多的不解,不是很熟練,所以我查找資料,進行一個總結(jié),希望可以鞏固知識,并且能幫助到需要的人,所以我會寫的比較清晰簡單明了點,若有不對之處,請大家糾正
Redux中subscribe的作用
redux的使用步驟過程
首先安裝redux
安裝命令:
npm install redux
redux使用過程(原理)
- 使用函數(shù)createStore創(chuàng)建store數(shù)據(jù)點
- 創(chuàng)建Reducer。它要改變的組件,它獲取state和action,
- 生成新的state 用subscribe監(jiān)聽每次修改情況
- dispatch 一個派發(fā)方法,將action 派發(fā)給reducer 更改state
代碼如下:
創(chuàng)建一個組件
import React, { Component } from 'react' import store from "./store"; import axios from 'axios'; export class DD extends Component { ? ? constructor(props){ ? ? ? ? super(props); ? ? ? ? this.state = store.getState(); ? ? ? ? //subscribe當(dāng)store中數(shù)據(jù)發(fā)生變化就會更新數(shù)據(jù) ? ? ? ? store.subscribe(()=>{ ? ? ? ? ? ? this.setState(store.getState()) ? ? ? ? }) ? ? } ? ? render() { ? ? ? ? return ( ? ? ? ? ? ? <div> ? ? ? ? ? ? ? ? hengheng,我很生氣 ? ? ? ? ? ? </div> ? ? ? ? ) ? ? } } export default DD
主要用subscribe監(jiān)聽store中每次修改情況
? ?store.subscribe(()=>{ ? ? ? ? ? ? this.setState(store.getState()) ? ? ? ? })
Redux的store.subscribe()監(jiān)聽
import createStore from 'Redux' const { store } = createStore(reducer) store.subscribe(放上view的更新函數(shù))//對于React 則是render和setState
此后 更新函數(shù)的每一次變化都會觸發(fā)view的重新自動渲染
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React?Native系列之Recyclerlistview使用詳解
這篇文章主要為大家介紹了React?Native系列之Recyclerlistview使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10ahooks封裝cookie?localStorage?sessionStorage方法
這篇文章主要為大家介紹了ahooks封裝cookie?localStorage?sessionStorage的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07React-router中結(jié)合webpack實現(xiàn)按需加載實例
本篇文章主要介紹了React-router中結(jié)合webpack實現(xiàn)按需加載實例,非常具有實用價值,需要的朋友可以參考下2017-05-05React 組件的狀態(tài)下移和內(nèi)容提升的操作方法
這篇文章主要介紹了React 組件的狀態(tài)下移和內(nèi)容提升,通過代碼講解了渲染性能的組件問題結(jié)合實例代碼給大家講解的非常詳細,需要的朋友可以參考下2022-11-11