2015-10-06 117 views
1

我自己在一個項目中工作,我正在使用Reactjs和Nodejs。瞭解如何在React中獲取數據。從後端到前端

我完成了Nodejs部分,我已經有了我需要從數據庫獲得的數據,我已經將它轉換成了json,並且準備好將這些數據發送到前端。

我所做的只是一個GET請求,其中前端的主要工具是axios。這個GET請求是爲了顯示賭場遊戲經銷商的簡單列表。

我需要的是一段簡短的代碼和解釋,以瞭解我在做什麼。我一直在閱讀所有信息,但對我來說並不是那麼容易,因爲我覺得無法將文檔中的示例適用於我的代碼,對不起,我只是一名初級開發人員。

這基本上是服務的一部分

import axios from 'axios'; 

const API_ENDPOINT = `${API_URL}/services`; 

const GetDealers = { 
    axios.get(`${API_ENDPOINT}/get-dealers/get-dealers`) 
    .then(function(response) { 
     console.log('get-dealers', response); 
    }) 

}; 

export default GetDealers; 

現在,我需要知道的是:我應該在actionsstores部分呢?

這就是我真正想弄明白的。知道如何處理ActionsStores,在組件中,我應該撥打action還是store

Angular對我來說很容易學習,但看起來好像React是針對至少有2年JavaScript經驗的人。我很難得到它。

+0

不要把自己看低了我們都只是開發者在那裏打同一場戰鬥! –

回答

2

我會研究Flux架構多一點。

基本上你想在你的代碼的「then」部分做的事情是發送一個行動到一個商店,更多的信息在調度員here

到調度員打電話,我經常使用的一個例子如下:

 Dispatcher.handleViewAction({ 
      actionType: ActionConstants.RECEIVE_STORES, 
      stores: stores 
     }); 

與調度員處理上面的動作,它就會發送到每個門店已註冊的調度員處理有效載荷。這裏面是一個switch語句來處理相關數據。

DirectoryStore.dispatchToken = Dispatcher.register(function(payload) { 

let action = payload.action; 
console.log(action) 
switch (action.actionType) { 
    case "RECEIVE_STORES": 
     setDirectoryStores(action.stores); 
     break; 
    case "FILTER_STORES": 
     filterDirectoryStores(action); 
     break; 
    default: 
     return true; 
     break; 
} 
DirectoryStore.emitChange(); 

return true; 
}); 

一旦通過switch語句,就可以發出你的內部存儲由視圖聽取事件 。

商店:

emitChange() { 
    this.emit('change'); 
}, 

addChangeListener(callback) { 
    this.on('change', callback); 
}, 

removeChangeListener(callback) { 
    this.removeListener('change', callback); 
}, 
getDirectoryStores() { 
    return {"data" : _directoryData}; 
} 

查看:

 componentWillMount() { 
     DirectoryStore.addChangeListener(this._onChange); 
    }, 
    componentDidMount(){ 
     StoreActionCreator.getDirectoryStores(); 
    }, 
    componentWillUnmount() { 
     DirectoryStore.removeChangeListener(this._onChange); 
    }, 
    _onChange() { 
     let data = DirectoryStore.getDirectoryStores(); 

     this.setState({ 
      data: data.data 
     }); 
    } 
+0

emitChange - 這會在商店dispatchToken調用 –

+0

中調用,但等一下,Dispatcher.handleViewAction和DirectoryStore.dispatchToken進入服務中的.then'內部嗎?我有點困惑。 – NietzscheProgrammer

+0

將調度標記放置在您用作存儲的文件中,因爲標記是存儲對象的擴展 –

相關問題