【问题标题】:Trouble populating state via axios通过 axios 填充状态时遇到问题
【发布时间】:2017-02-01 21:37:18
【问题描述】:

我正在尝试使用简单的 json API (json-server --watch db.json) 来填充通量存储的状态。我正在从父组件的componentWillMount 调用 store 的函数来使用 Axios 加载数据。

我一直在查看以下教程以供参考: http://mediatemple.net/blog/tips/loading-and-using-external-data-in-react/ https://www.toptal.com/react/tips-and-practices 和其他人。

这是我要提取的 JSON 数据:

[
  {
    "complete": "false",
    "edit": "false",
    "id": "uuid()",
    "text": "Go Shopping"
  },
  {
    "complete": "false",
    "edit": "false",
    "id": "uuid()",
    "text": "Pay Water Bill"
  }
]

db.json 要点https://gist.github.com/WebRuin/548f6073ca533016503d34c36116b8de

这是我打电话的 Flux 商店的摘录:

import { EventEmitter } from 'events'
import dispatcher from '../dispatcher'
import axios from 'axios'

import uuid from 'uuid4'

class TodoStore extends EventEmitter {
  constructor() {
    super()
    this.state = {
      todos: [],
      showCompletedTodos: true,
      showIncompletedTodos: true
    }

    this.deleteTodo = this.deleteTodo.bind(this)
    this.toggleTodo = this.toggleTodo.bind(this)
    this.toggleShowCompletedTodos = this.toggleShowCompletedTodos.bind(this)
    this.toggleShowIncompletedTodos = this.toggleShowIncompletedTodos.bind(this)
  }
...

fetchUserState() {
    let th = this
    console.log(th)
    this.serverRequest = 
      axios.get('http://localhost:3000/todos')
        .then(function(result) {
          console.log(result.data)
          th.state.todos = result.data
        })
  }

}

const todoStore = new TodoStore
dispatcher.register(todoStore.handleActions.bind(todoStore))

export default todoStore

完整文件的要点: https://gist.github.com/WebRuin/efbbf4296c566f6eb58cc6d641bee4ba

控制台日志向我显示 axios 请求已用我想要的数据完成,this 的日志显示 this.state.todos 正在填充,但 Chrome 的反应插件不显示数据,因此应用程序不显示数据。

我做错了什么?

【问题讨论】:

  • 代替“th.state.todos = result.data”,试试“th.setState({ todos: result.data })”
  • 很好的问题。

标签: reactjs flux axios


【解决方案1】:

Andy 是对的,除了构造函数,我们应该总是使用setState(),它在设置状态时是异步工作的。


来自here12


然而,这对于普通的 React 来说是正确的。在 Flux 中,我们应该忘记 setState 方法,而只使用商店。这是文章中的信息。

我为我的 Flux 导航创建了一张图片,它可能会对你有所帮助。


通常您应该通过 axios 加载数据,而不是通过 componentWillMount(),但您可以使用 Flux 操作流。 但是,您仍然可以使用componentWillMount() 来创建操作。

【讨论】:

  • 这增加了一个很好的视角。谢谢,仍然不确定如何从使用 EventEmiter 创建的商店中使用 this.setState
  • Git 集线器。应该有例子@Tithos
  • 我的意思是在 github 上搜索解决方案 @Tithos。它可能会有所帮助。
【解决方案2】:

永远不要直接修改状态对象。始终使用setState()

【讨论】:

  • this.setState 可以从EventEmitter 调用。我以前遇到过。以我有限的经验,this.setState 只能从 `React.Component' 或 'React.creatClass' 调用
  • this.setState 不能从EventEmitter 调用我的意思是
  • 您的代码修改了组件类中fetchUserState 中的状态
  • 这是我在尝试这个 `Uncaught (in promise) TypeError: th.setState is not a function at TodoStore.js:58'时得到的结果
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2011-05-22
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2022-08-06
  • 2019-11-19
  • 2015-06-16
相关资源
最近更新 更多