iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 26
0

快結束了,不知不覺已經26天了。

這邊提醒一下 我是使用react_on_rails內建的redux產生器
rails generate react_on_rails:install --redux
所以可以前後端都知道redux store

先來看看我們的store

//stores/SharedReduxStore.jsx

import { combineReducers, applyMiddleware, createStore, compose } from 'redux';
import thunk from 'redux-thunk';

import reducers from '../reducers';
import { initialStates } from '../reducers';

export default (props, railsContext) => {
  const combinedReducer = combineReducers(reducers);
  const newProps = { ...props, railsContext };
  const { $$readingListState } = initialStates;
  const initialState = {
    $$readingListStore: $$readingListState.merge({
      ...props,
      railsContext
    }),
  };
  const store = createStore(
                             combinedReducer,
                             initialState,
                             compose(
                                applyMiddleware(thunk),
                                window.devToolsExtension ? window.devToolsExtension() : f => f
                             )
                           )
  return store;
  //return applyMiddleware(middleware)(createStore)(combinedReducer, initialState);
};

建立store的方法很多種,我是使用最常見的createStore。
為什麼我稱它中控室?他設定reducer,設定初始狀態,設定middleware,
把很多要管理的,要設定的,都在建立store的時候處理完。
甚至,state都要透過她去取得,這樣,有沒有像中控室?

好,再來是startup這支,去註冊store,讓後端rails可以知道store:

# startup/HelloWorldApp.jsx
import React from 'react';
import ReactOnRails from 'react-on-rails';

import { Provider } from 'react-redux';

import ReadingList from '../containers/ReadingList';

import SharedReduxStore from '../stores/SharedReduxStore';
import ReadingListContainer from '../containers/ReadingListContainer';

const ReadingListApp = (props, _railsContext) => {
  const store = ReactOnRails.getStore('SharedReduxStore');
  const reactComponent = (
    <Provider store={store}>
      <ReadingListContainer />
    </Provider>
  );
  return reactComponent;
};
ReactOnRails.register({, ReadingListApp });
#註冊SharedReduxStore
ReactOnRails.registerStore({
  SharedReduxStore,
});

最後,是View,要去新增redux_store:

#app/views/books/home.html.erb
<h1 class="alert alert-info this-works">Hello World</h1>
<%= redux_store("SharedReduxStore", props: @books) %>
<%= react_component("ReadingListApp",  prerender: false, trace: true, id: "ReadingListApp-react-component-0") %>

整個Redux就差不多囉!!
最後,就仿照redux的文件,明天就Po上整個範例,來結束redux整合的部分!
範例可參照Github
希望我明天一早衝浪順利!


上一篇
Day 25, Redux Reducers - State管理大師
下一篇
Day 27, Example: Reading List
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30

尚未有邦友留言

立即登入留言