react專案中使用狀態管理

2021-10-06 22:44:19 字數 1922 閱讀 4172

1. 安裝 redux 

2.  安裝 react-redux

3.在src目錄下建立乙個store目錄

import  from 'redux'

// 1. 定義

const notices = (state = , action ) =>

default:

return state

}}// 2. 建立

const store = createstore (notices)

export default store

4. 在react更節點中使用 provide 

// 1. 引入provider

import from 'react-redux'

// 2. 引入store

import store from './store/index'

// 3. 匯入資料

...

5. 在元件中使用

// 匯入connect 連線元件

import from 'react-redux'

// 1. 使用mapstatetoprops 將store 資料派發給props中

const mapstatetoprops = (state, ownprops) =>

}// 2. 建元件進行連線

export default connect( mapstatetoprops )(index)

6.dispatch 觸發

)}} > 切換
7. 多個reduce合併 combinereducers 

import  from 'redux'

import norices from './reducers/norices'

import products from './reducers/products'

//1.合併reducers

const rootreducers = combinereducers( )

// 2. 建立

const store = createstore (rootreducers)

export default store

8. 使用非同步action 觸發dispatch

1. 修改store/index.js

import norices from './reducers/norices'

import products from './reducers/products'

import thunk from 'redux-thunk'

//1.合併reducers

const rootreducers = combinereducers( )

// 2. 建立

export default store

2. 建立actions/products.js

export const loadproduct = (payload) => )

} }

3. 使用

import react, from 'react'

import from 'react-redux'

import from '../../../store/actions/products'

function index(props) )

)},[props])

return (

列表)}

const mapstatetoprops = (state) =>

export default connect(mapstatetoprops)(index)

React專案中使用Mobx狀態管理(二)

並上一節使用的是普通的資料狀態管理,不過官方推薦使用裝飾器模式,而在預設的react專案中是不支援裝飾器的,需要手動啟用。官方參考 一 新增配置 官方提供了四種方法,方法一 使用typescript,顧名思義該方法是專案使用typescript時的配置 方法二 使用babel preset mobx...

React專案中使用Mobx狀態管理(一)

1 安裝 1 yarn add mobx mobx react 2 新建store index.js,存放資料 以下思路僅限於父子元件的簡單應用 1 import from mobx 2 觀察器 狀態 4 timer 1005 方法8 9 方法 11 console.log increase 13 ...

在專案中使用react

1.執行 cnpm install react react dom s react安裝包 專門用於建立元件和虛擬dom的,同時元件的生命週期都在這個包中 react dom安裝包 專門進行dom操作的,最主要的應用場景就是reactdom.render 2.在index.html頁面中建立容器 di...