redux相關

react 框架有本身的一些語法,如 jsx, 組件化。可是組件之間的數據傳遞,會成爲一大難題。因此就不得不使用一個數據驅動的框架, 那就是 reduxjavascript

1. 建立 store

大多數狀況下,會在 /src 目錄下建立一個 store 的文件夾,來管理 redux 相關。
先上圖:java

redux流程圖

因此,首先得有一個store, 那麼在 /src/store 文件夾下建立 index.jsreact

/src/store/index.js
// 引入須要用到的方法
import { createStore, compose, applyMiddleware } from 'redux'
// 引入 reducer
import reducer from './reducer'
// 引入 redux 中間件 thunk : 目的爲了可使action 返回一個 函數方法。
// 使用redux的chrome插件, 以及爲了使用 redux 的 中間件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// 建立 store
const store = createStore(reducer, composeEnhancers(
    applyMiddleware(thunk)
))

// 導出 store
export default store
複製代碼

2.建立 reducer

store 其實是沒法操做 數據 state, 它只能將 action 發送給 reducer ,根據 reducer 返回新得 newState 來替換之前得數據 state。(記住,不容許直接更改 state)chrome

/src/store/reducer.js
// 建立 默認的 state
const defaultState = {
    something: ''
}
// 建立 reducer reducer默認是一個函數,接受兩個參數,分別是 state 和 action
// state 是 原始的state, 而 action ,若是用戶提交 dispatch, 那麼這裏就會接收到
const reducer = (state, action) => {
    // action 會有一個 type 屬性,還可能會伴隨着 其餘須要的自定義屬性
    if (action.type === ??) {
        // 深拷貝
        const newState = JSON.parse(JSON.stringify(state))
        // 賦值 用戶傳輸過來的 data
        newState.something = action.data
        // 返回新的state "newState"
        return newState
    }
    return state
}

複製代碼

3.建立 actionTypes 和 建立 actionCreators

由於隨着愈來愈多的數據須要管理,咱們不該該直接在組件的業務邏輯裏,直接手寫 action.type,容易出現拼寫錯誤,可是不會報錯,並且直接 dispatch 手寫的 action 會很難去維護,因此須要建立 actionTypesactionCreatorsredux

/src/store/actionTypes.js

export const CHNAGE_SEARCH_LIST = 'change_search_list'
export const LOGIN = 'login'
複製代碼

/src/store/actionCreators.js

import * as actionTypes from './actionTypes'

// 假設有這樣的一些action
const searchList = (data) => ({
    type: actionTypes.CHANGE_SEARCH_LIST,
    data
})

const userLogin = (data) => ({
    type: actionTypes.LOGIN,
    data
})
複製代碼

// 引入 store
import store from './store'
// 引入 action 生成器
import { searchList, userLogin } from './store/actionCreators.js'
render() {
    return (<div>...</div>)
}

// 尋找方法
handleClickSearchBtn(data) {
    // dispatch 這個 生成的action
    store.dispatch(searchList(data))
}
// 登陸邏輯方法
handleLogin(data) {
    // dispatch 生成的action
    store.dispatch(userLogin(data))  
}

複製代碼

以上~app

相關文章
相關標籤/搜索