【问题标题】:setState start to work recursively in React.jssetState 开始在 React.js 中递归工作
【发布时间】:2015-01-24 01:30:17
【问题描述】:
我开始使用 react.js 并创建一个组件 Box,state = {pageNumber: 1, dataForTable:''}。我在其中插入了两个组件 - 分页和表格。当单击分页时,它会为 Box 提供页数。盒子状态改变,然后渲染,然后分页也渲染。然后我将 ajax 设置为服务器,获取表的新数据,然后第二次进行 Box 渲染以渲染 Tables。
我应该在哪个函数中放置 ajax 逻辑?当我把它放在componentDidUpdate setState 开始递归工作。
将来<Box/ > 中将有更多组件,这些组件将更改<Tables />。
【问题讨论】:
标签:
javascript
ajax
pagination
reactjs
【解决方案1】:
据我了解,这是您的设置:
var React = require('react');
var ComponentBox = React.createClass({
render: function() {
return (
<div>
<Table />
<Pagination />
</div>
);
}
});
module.exports = ComponentBox;
- 您的表格组件不应该处理数据,您应该将数据“提供”给您的组件。所以你应该在你的表格组件中有一个接收数据的道具。
- 分页组件应该向 ComponentBox 传递一个事件,告诉 ComponentBox 获取数据 - 所以 ajax 应该发生在您的 ComponentBox 中(如果您愿意,请阅读有关通量的更多信息)
这是为您推荐的解决方案
var React = require('react');
var ComponentBox = React.createClass({
handlePageChange: function(startIndex, size) {
// do your ajax here
// set your data to state which causes re-render
},
render: function() {
return (
<div>
<Table data={this.state.tableData} />
<Pagination onPageChange={this.handlePageChange} />
</div>
);
}
});
module.exports = ComponentBox;
在你的分页组件中,记得通过 props onPageChange =) 传递信息
希望这对你来说已经足够清楚了。