如何在React FLUX中创建API调用?

时间:2016-09-06 13:39:19

标签: javascript html reactjs reactjs-flux

我是新手。我挣扎了10个小时来解决这个问题。我创建了一个示例待办事项应用程序。最初我想从服务器加载一些数据。但我不知道如何获取这些数据。当我点击按钮时,我能够获取数据。请有人帮我解决这个问题。因为我试图长时间完成这个。

我的示例代码,

App.js

var React  = require('react');
import * as TodoActions from "./js/Actions";
import TodoStore from "./js/stores/EventLists";

export class EventListing extends React.Component {
  constructor() {
    super();
    this.getTodos = this.getTodos.bind(this);
    this.state = {
      todos: TodoStore.getAll(),
    };
  }

  componentWillMount() {
    TodoStore.on("change", this.getTodos);
  }

  componentWillUnmount() {
    TodoStore.removeListener("change", this.getTodos);
  }

  getTodos() {
    this.setState({
      todos: TodoStore.getAll(),
    });
  }

  reloadTodos() {
    TodoActions.reloadTodos();
  }

  render() {
    var List = this.state.todos.map(function(el, i){
      return <li key={i}>
        <div>{el.STA_NAME}</div>
      </li>;
    });
    return (
      <div className="listing">
        <button onClick={this.reloadTodos.bind(this)}>Reload!</button>
        <ul>
          {List}
        </ul>
      </div>
    );
  }
}

var Events = React.createClass({
    render:function(){
        return (<div>
               <EventListing />
        </div>);
    }
});

module.exports = Events;

Store.js

import EventEmitter from 'events';
import dispatcher from "../dispatcher"

class EventLists extends EventEmitter {
  constructor(){
      super();
      this.todos = [{}];
  }
  createTodo(text) {
    const id = Date.now();

    this.todos.push({
      id,
      text,
      complete: false,
    });

    this.emit("change");
  }
    getAll() {
    return this.todos;
    }
  handleActions(action) {
    switch(action.type) {
      case "CREATE_TODO": {
        this.createTodo(action.text);
        break;
      }
      case "RECEIVE_TODOS": {
        this.todos = action.todos;
        this.emit("change");
        break;
      }
    }
  }
};

const eventLists = new EventLists;
dispatcher.register(eventLists.handleActions.bind(eventLists));
export default eventLists;

Action.js

import dispatcher from "./dispatcher";

export function createTodo(text) {
  dispatcher.dispatch({
    type: "CREATE_TODO",
    text,
  });
}

export function deleteTodo(id) {
  dispatcher.dispatch({
    type: "DELETE_TODO",
    id,
  });
}

export function reloadTodos() {
    var loadData;
    $.ajax({
        url:url,
        type:'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType:'json',
        success:function(data) {
            loadData = data;
        }.bind(this)
    });
    dispatcher.dispatch({type: "FETCH_TODOS"});
    setTimeout(() => {
        console.log(loadData);
        dispatcher.dispatch({type: "RECEIVE_TODOS", todos: loadData});
    }, 1000);
}

Dispatcher.js

import { Dispatcher } from "flux";

export default new Dispatcher;

2 个答案:

答案 0 :(得分:2)

我已经尝试过您的代码,您需要更改的唯一内容是Action.js。

由于ajax调用,您必须等到响应回来并在事件FETCH_TODOS的ajar调用和事件RECEIVE_TODOS的成功函数之前使用调度程序。

超时是等待ajax响应的坏主意。

export function reloadTodos() {
    dispatcher.dispatch({type: "FETCH_TODOS"});
    var loadData;
    $.ajax({
        url:url,
        type:'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType:'json',
        success:function(data) {
            loadData = data;
            dispatcher.dispatch({type: "RECEIVE_TODOS", todos: loadData});
        }
    });
}

<强> EDITTED

好的,现在我了解了一点

请将此方法添加到Action.js

export function loadData() {
    dispatcher.dispatch({ type: "FETCH_TODOS" });
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos/",
        type: 'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json',
        success: function(response) {
            dispatcher.dispatch({ type: "RECEIVE_TODOS", todos: response });
        }
    });
}

并在构造函数方法的app.js上调用它,这样就可以在最开始时初始化数据

export class EventListing extends React.Component {
  constructor() {
    super();
    this.getTodos = this.getTodos.bind(this);
    this.state = {
      todos: TodoStore.getAll(),
    };
    TodoActions.loadData();
  }

请注意,由于通过,您将在处理RECEIVE_TODOS时正确获取数据

答案 1 :(得分:0)

如果要在初始加载时加载数据,则应添加一个调用reloadTodos操作的componentDidMount。

componentDidMount() {
  TodoActions.reloadTodos();
}

确保在DidMount而不是WillMount中调用此副作用,以便新的存储状态将正确触发重新呈现以显示您的数据(它应该是非常即时的)

最后,正如@ pachon_1992所说你不应该使用超时来等待你的ajax响应而是你应该成功发送