React Js,在ajax响应之前进行回流渲染
React Js, Reflux render before ajax response
我想通过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,所以可能有更好的方法,但我天真的方法是:
-
在编写组件时,要考虑到第一次呈现时不会有数据,所以要让代码更安全,
-
在
success
回调中,使用新数据再次渲染组件。
但是,Reflux可能有一种我不知道的处理REST的内置方式。
相关文章:
- IE上的新XMLHttpRequest()出现JS Ajax未指定错误
- 含义模式:'中止'在JS Ajax请求中
- React JS Ajax Data Loop
- Angular.js ajax和应用程序不起作用
- JS(ajax)数组-带有HTML的输出和样式
- django-cant将选定的标签传递到js(ajax代码)
- 如何在JS/Ajax中每秒提取PHP函数
- JS/Ajax:抓取输入字段值,无需刷新或点击按钮
- JS/AJAX:提交时不刷新或按钮单击不触发输入
- 如何获取
- 元素 js/ajax 的 Id 值
- 如何使用 JS AJAX 获取 XML 标记的名称
- JS/Ajax w/ 带节流的按键
- jQuery:处理混合的html/js ajax响应
- 停止 js ajax 函数中的 html 提交按钮
- JS/AJAX:隐藏/显示选择框
- 哎呀js + $.ajax 将变量传递给父类
- 将带有 datatype:jsonp 的 jQuery ajax 更改为纯 JS ajax
- 提交后显示 JS/Ajax 消息
- Rails + JS + Ajax request
- jquery.couchdb.js Ajax 成功/错误未被调用