我正在做一个简单的待办事项应用程序对应用程序工作正常时,我将数据存储在预定义的对象。 但现在我是从用ajax的链接(休息)让我的数据,让问题与此, 路径 - 页/ todo.js如何等待ajax响应,然后定义对象
import React from "react";
import Todo from "../components/Todo";
import * as TodoActions from "../actions/TodoActions.js";
import TodoStore from "../stores/TodoStore";
export default class Settings extends React.Component {
constructor(){
super();
this.getTodos=this.getTodos.bind(this);
this.state={
todos: TodoStore.getAll(),
};
console.log("STATE",this.state.todos);
}
componentDidMount(){
TodoStore.on("load",this.getTodos);
}
getTodos()
{
this.setState({
todos:TodoStore.getAll(),
});
}
reloadTodos(){
TodoActions.reloadTodos();
}
render() {
const {todos}=this.state;
const TodoComponents=todos.map((todo)=>{
return <Todo key={todo.id} {...todo}/>;
});
return (
<div>
<button onClick={this.reloadTodos.bind(this)}>Reload!!</button>
<h1>TODO.net</h1>
<ul>{TodoComponents}</ul>
</div>
)
}
}
路径-stores /藤
import {EventEmitter} from "events";
import * as $ from "jquery";
import dispatcher from "../Dispatcher";
class TodoStore extends EventEmitter
{
constructor(){
super()
this.todos=[];
}
createTodo(text)
{ const id=Date.now();
this.todos.push({
id,
text,
complete:false
});
this.emit("change");
}
getAll(){
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/chitranks/todo',
success: function(data) {
console.log("here",data);
this.todos=data;
window.todos=this.todos;
}.bind(this),
error: function() {
alert('error GET connecting to REST');
}.bind(this)
});
return this.todos;
}
handleActions(action) {
switch(action.type){
case "CREATE_TODO":{
this.createTodo(action.text);
}
case "RECEIVED_TODOS":{
this.todos=action.todos;
this.emit("change");
}
}
}
}
const todoStore=new TodoStore;
dispatcher.register(todoStore.handleActions.bind(todoStore));
window.dispatcher=dispatcher;
export default todoStore;
时我在控制台待办事项I型可以看到的数据,但它不呈现(显示未定义)中的页面
并且还/ todo.js文件的对象是未定义
您可以在JavaScript中使用的回调函数,使其以 – Kebeng
您不能从异步立即检索数据执行函数,因为它需要时间来接收响应请参阅[如何从异步函数检索数据](http://stackoverflow.com/q/14220321/2902660) – Pineda