2016年3月23日 星期三

redux 可以使用多個不同 store 嗎?

redux 可以使用多個不同 store 嗎?

原本很直覺的回答這個問題是,可以的!
但是透過 google 一段時間之後,才深入去找問題的本身,發現 redux 作者希望,除非必要性的需求,否則盡量使用『單一 reduxer 對應到單一 store』 ,本持的精簡的精神處理物件。

處理範例方式,GitHub

可以採用以下的方式,用多個不同 reducer 包裝起來
// reducers.js
export step1 from './step1'
export step2 from './step2'

// constants.js
export const STEP1_COMPLETED = 'STEP1_COMPLETED'
export const STEP2_COMPLETED = 'STEP2_COMPLETED'

// step1.js
import { STEP1_COMPLETED } from './constants'

const initialStep1State = {
  email: '',
  password: '',
}

export function step1(state = initialStep1State, action) {
  switch (action.type) {
    case STEP1_COMPLETED:
      return { ...state, email: action.email }

    default:
      return state
  }
}

// step2.js
import { STEP2_COMPLETED } from './constants'

const initialStep2State = {
  firstname: '',
  lastname: '',
}

export function step2(state = initialStep2State, action) {
  switch (action.type) {
    case STEP2_COMPLETED:
      return { ...state, firstname: action.firstname, lastname: action.lastname }

    default:
      return state
  }
}

// actions.js
import post from 'some-networking-lib'
import { STEP1_COMPLETED, STEP2_COMPLETED } from './constants'

export function saveStep1(data) {
  return (dispatch) => {
    post('/step1', data).then(({ email }) => {
      dispatch({ type: STEP1_COMPLETED, email })
    })
  }
}

export function saveStep1(data) {
  return (dispatch) => {
    post('/step2', data).then(({ firstname, lastname }) => {
      dispatch({ type: STEP2_COMPLETED, firstname, lastname })
    })
  }
}

// App.js
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'redux/react';
import * as reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);
const store = createStoreWithMiddleware(reducers);

export default class App {
  render() {
    return (
      <Provider store={ store }>
        { () => <FormWithStepsApp /> }
      </Provider>
    );
  }
}
ref, You don't need multiple stores to achieve that but multiple reducers. ...

原作者的回答

資料中指出 redux , 建議採用 one store.
There are edge cases when you might use multiple stores (e.g. if you have performance problems with updating lists of thousands of items that are on screen at the same time many times per second). That said it's an exception, and in most apps you never need more than a single store.

Why do we stress this in the docs? Because most people coming from Flux will assume multiple stores is the solution to making update code modular. However Redux has a different solution for this: reducer composition.

沒有留言:

張貼留言

Facebook