React Js,在ajax响应之前进行回流渲染

React Js, Reflux render before ajax response

本文关键字:Js ajax 响应 React      更新时间:2023-09-26

我想通过api调用获得我的用户列表,并用数据呈现一个表。

目前我可以得到数据,但当我试图显示它时,我有一个错误。

我认为react是在api调用结束之前渲染,不明白为什么。

这是我的代码:

var Actions = Reflux.createActions([
  "fetchList"
]);

这是我的商店:

var bannersStore  = Reflux.createStore({
  users: { data : {}},
  listenables: [Actions],
  init: function() {
    this.fetchList();
  },
  fetchList: function(){
    var self = this;
    reqwest({
      url: 'http://localhost:9080/api/member.json',
      method: 'get',
      success: function (resp) {
        console.log('fetch complete');
        self.users = resp;
        self.trigger({users :resp});
      }
    });
  }
});

这是我的React课程:

var Users = React.createClass({
    getInitialState: function() {
        return {users : UsersStore.fetchList()};
    },
    render: function() {
        var usersRows = this.state.users.data.map(function(user, i) {
              return (
                  <tr key={i}>
                      <td><Link to="user" params={{ id: user.id }}>{user.attributes.firstname + ' ' + user.attributes.lastname}</Link></td>
                      <td>{user.attributes.email}</td>
                      <td>{user.status}</td>
                      <td>{user.language}</td>
                  </tr>
              )
          });
          return (
              <div>
                  <table className="table table-striped">
                      <thead>
                      <tr>
                          <th>Name</th>
                          <th>Image</th>
                          <th>URL</th>
                          <th>Active?</th>
                      </tr>
                      </thead>
                      <tbody>
                      { usersRows }
                      </tbody>
                  </table>
              </div>
          )
        }
});

this.state.users.data是未定义的,我有一个错误(未定义)。

谢谢你的帮助。

我建议使用这种模式。回流模式的示例可以在https://github.com/calitek/ReactPatternsReact.14/ReFluxSuperAgent.

    getInitialState: function() {
        return {users : {data: []}};
    },
    componentDidMount() {
      this.unsubscribe = UsersStore.listen(this.storeDidChange);
      Actions.fetchList();
    },
    componentWillUnmount() { this.unsubscribe(); },
    storeDidChange(newData) {
      this.setState(newData);
    },

您是否希望UI在请求成功之前冻结?

这里发生的是异步执行请求。一旦成功,您的success回调将被触发,这是您可以更新React组件的地方。

我不熟悉Reflux,所以可能有更好的方法,但我天真的方法是:

  1. 在编写组件时,要考虑到第一次呈现时不会有数据,所以要让代码更安全,

  2. success回调中,使用新数据再次渲染组件。

但是,Reflux可能有一种我不知道的处理REST的内置方式。