Redux中subscribe的作用及說明
更新時間:2023年10月07日 11:30:58 作者:*唔西迪西*
由于redux使用這方面有很多的不解,不是很熟練,所以我查找資料,進行一個總結,希望可以鞏固知識,并且能幫助到需要的人,所以我會寫的比較清晰簡單明了點,若有不對之處,請大家糾正
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當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的重新自動渲染
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
React Hook useState useEffect componentD
這篇文章主要介紹了React Hook useState useEffect componentDidMount componentDidUpdate componentWillUnmount問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
react項目升級報錯,babel報錯,.babelrc配置兼容等問題及解決
這篇文章主要介紹了react項目升級報錯,babel報錯,.babelrc配置兼容等問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
React ts模式使用http-proxy-middleware代理時訪問報404問題
這篇文章主要介紹了React ts模式使用http-proxy-middleware代理時訪問報404問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
在React中使用Antd上傳并讀取Excel文件的詳細步驟
在React中使用Antd組件庫來上傳并讀取Excel文件,可以結合antd的Upload組件和xlsx庫來實現(xiàn),以下是一個詳細的步驟和示例代碼,展示如何在React應用中實現(xiàn)這一功能,感興趣的小伙伴跟著小編一起來看看吧2025-01-01

