天天看點

react中使用redux進行狀态存儲

  1. 安裝redux、react-redux
npm install redux
npm install react-redux 
//為了防止不小心修改state中的資料引入immutable,變成不可修改的資料
npm install immutable
npm install redux-immutable
           

2.在外層App.js中引入Provider

react中使用redux進行狀态存儲

3.在元件中引入connect來進行store中資料的接收和派發改變

import { connect } from 'react-redux';
// 修改export部分的代碼
export default connect(mapStateToProps, mapDispatchToProps)(Header)
           
react中使用redux進行狀态存儲
react中使用redux進行狀态存儲

4.建立store的檔案夾,建立index.js 和reducer.js兩個檔案

index.js

react中使用redux進行狀态存儲

reducer.js

react中使用redux進行狀态存儲

使用redux-immutable之後,在store中擷取header就不是使用簡單的state.header了而是state.get(‘header’);

react中使用redux進行狀态存儲
react中使用redux進行狀态存儲

5.在header元件中建立header元件的store狀态存儲

reducer.js

// 安裝immutable元件之後
import { fromJS } from 'immutable';
// formJS的用法如下,将state總存儲資料變成不可改變的資料
// 當使用formJS之後用state.set('focued', true)來傳回新state的對象
// 同理元件中隻用的時候要使用get的方法擷取該值。
state.get('focued')
           
react中使用redux進行狀态存儲
react中使用redux進行狀态存儲
react中使用redux進行狀态存儲

6.建立actionType.js來存儲type的常量

react中使用redux進行狀态存儲

7.建立creatAction.js來進行資料的派發

react中使用redux進行狀态存儲

在元件中引入

react中使用redux進行狀态存儲

派發type

react中使用redux進行狀态存儲

8.通過調用props中的資料進行應用

react中使用redux進行狀态存儲