2017-08-08 6 views
0

私は私のプロジェクトにインポートしていますモックJSONファイル、持っている:Mock jsonファイルプロジェクトにどのように組み込むのですか?

import data from './config/data.json'; 

私は私のプロジェクトでそれを含めるにはどうすればよいので、すべてのコンポーネントがそれを使用することができますか?

私はあなたがお店に追加することができreact-router

render(
    <Provider store={store}> 
     <Router history={browserHistory} routes={routes} /> 
    </Provider>, 
    document.getElementById('root') 
); 

答えて

0

私が正しく理解していれば、古い店舗データを読み込みたいですか? createStore docs

createStore(reducer, [preloadedState], [enhancer]) 

はい、それは以前に

を保存したストアオブジェクトですpreloadedState引数を経由してストアを作成しながら、あなたがそれを注入することができますが、 詳細ヘッド用はありません、それはそう設定などの汎用的なデータですか:

ベストプラクティスとそれをデバッグする機能を後で実行するには、Reduxのフロー アクションタイプ(例:GET_CONFIG)を追加し、それを減速機にディスパッチしますこの

// Create Action Type 
 
const GET_CONFIG = 'GET_CONFIG'; 
 

 
// Import json (you might need to handle webpack json-loader) 
 
import config from './config/data.json'; 
 

 
// Dispatch it (you can access the dispatch method from the store directly, outside the connect function) 
 
store.dispatch({type: GET_CONFIG, config}); 
 
render(
 
    <Provider store={store}> 
 
     <Router history={browserHistory} routes={routes} /> 
 
    </Provider>, 
 
    document.getElementById('root') 
 
);

のような
0

を使用しています。どのような状態管理を使用しているのかよく分かりませんが、ストアのコンストラクタでdata.jsonオブジェクトをインポートすると、デフォルト値を設定できるはずです。データの反応面では、ストアにアクセスしてdata.jsonデータにアクセスできます。

// YourStore.js 
import data from './config/data.json'; 
class YourStore{ 
    constructor() { 
     this.loadedData = data; 
    } 
} 

// entry.js 
import YourStore from './stores/YourStore.js'; 
const store = new YourStore(); 
render(
    <Provider store={store}> 
     <Router history={browserHistory} routes={routes} /> 
    </Provider>, 
    document.getElementById('root') 
); 
0

あなたのcreateStore機能を初期状態として(またはその一部として)あなたのJSONファイルからデータを渡すことができます。それは、アプリ全体のあなたのredux店を通じて利用可能になります。

this.state = { 
source: data; // which is => import data from './config/data.json'; 
} 

でのごPublicLayoutコンストラクタで

<Route path="/" component={PublicLayout}> 
    <IndexRoute component={LoginPage}></IndexRoute> 
    <Route path="/login" component={LoginPage}></Route> 
</Route> 

のようなあなたのメインのレイアウトファイルで

const initialState = { 
    data, 
    ...otherData, 
} 

const store = createStore(combineReducers({ 
    ...Reducers, 
    router: routerReducer, 
    }), 
    initialState, 
)); 

render(
    <Provider store={store}> 
     <Router history={browserHistory} routes={routes} /> 
    </Provider>, 
    document.getElementById('root') 
); 
0

は()次に、あなたのrenderメソッドで子コンポーネントへの小道具としてそれを渡します。 あなたはどのコンテキストで使用しているのかわかりませんが、これが役立つと思います。

また、Reduxを使用し、enter code hereを還元剤として使用し、このjsonデータを還元状態に割り当てて、アプリ内のどこにでもアクセスすることもできます。

また、最も簡単な方法では、Webpackファイルにエイリアスを使用して、 import data from './config/data.json';をコードのどこからでもアクセスできるグローバルパスにしてください。 Webpackは残りを処理します。

関連する問題