【问题标题】:React Js, Reflux render before ajax responseReact Js, Reflux 在 ajax 响应之前渲染
【发布时间】:2025-12-27 05:45:17
【问题描述】:

我想通过 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 未定义,我有一个错误(未定义)。

感谢您的帮助。

【问题讨论】:

    标签: javascript ajax reactjs refluxjs


    【解决方案1】:

    我会建议这种模式。可以在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);
        },

    【讨论】:

      【解决方案2】:

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

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

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

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

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

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

      【讨论】: