MobX http调用Rest API并返回Observable

时间:2017-05-31 17:07:30

标签: promise observable mobx mobx-react

我正在尝试使用MobX。我的问题是

  1. MobX是否附带内置的http片段?如果是,那么名称/功能是什么?
  2. 如果#1的答案是否定的,我使用axios怎样才能将已解决的承诺转换为我的observable?
  3. 我知道以下内容不正确。实现这一目标的常用方法是什么?

    export class TodoStore {
      @observable todos = [];
      ....
      fetchTodo() {
        axios.get("http://rest.learncode.academy/api/reacttest/tweets")
          .then((response) => {
            response.data.map(item => {
              this.todos.push(new Todo(item));
          })
          .catch((err) => {
            ....
          });
        });
      }
    }
    

1 个答案:

答案 0 :(得分:0)

这很有效。我测试了它。

TodoStore.js

class Todo {
  @observable value
  @observable id
  @observable complete

  constructor(value) {
    this.value = value
    this.id = Date.now()
    this.complete = false
  }
}

export class TodoStore {
   @observable todos = []
   @observable filter = ""
   @computed get filteredTodos() {
     var matchesFilter = new RegExp(this.filter, "i")
     return this.todos.filter(todo => !this.filter || matchesFilter.test(todo.value))
   }
  ...... 
  fetchTodos() {
    axios.get("http://rest.learncode.academy/api/reacttest/tweets")
      .then((response) => {
        console.log("in axios ", response.data)
         response.data.map(item => {
           console.log("in axios ", item)
           this.todos.push(new Todo(item.text));
        });
      })
      .catch((err) => {
        console.log("in axios ", err)
      })
  }
}

TodoList.js

export default observer(
 class TodoList extends React.Component {
  componentWillMount() {              
   this.props.store.fetchTodos()  
  }

  ........
  render() {
    ........      
    return <div>
      <h1>todos</h1>
      ......
    </div>
  }
}
)