【问题标题】:Understanding how to get data in React. From backend to frontend了解如何在 React 中获取数据。从后端到前端
【发布时间】:2015-10-06 23:39:03
【问题描述】:

我一个人在一个项目中工作,我正在使用 Reactjs 和 Nodejs。

我已经完成了 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 经验的人准备的。我很难得到它。

【问题讨论】:

  • 不要卖空自己!我们都是同场竞技的开发者!

标签: javascript reactjs


【解决方案1】:

我会更多地研究 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
        });
    }

【讨论】:

  • emitChange - 这在商店 dispatchToken 调用中被调用
  • 但是等一下,Dispatcher.handleViewActionDirectoryStore.dispatchToken 进入服务中的 .then ?我有点困惑。
  • 将调度令牌放在您用于存储的文件中,因为令牌是存储对象的扩展
  • 我收到了这个:Uncaught ReferenceError: DirectoryStore is not defined
  • DirectoryStore 应该是您的助焊剂商店的名称
猜你喜欢
  • 2021-07-01
  • 2022-01-21
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多