在我的OnEnter回调中,我正在进行api调用以获取更多数据。获取的数据将添加到我拥有的元素数组中。当我向上滚动时,当组件返回视口时,会再次触发api调用。
有没有办法解决这个问题?
代码示例: 好的,让我清理一下:@jmeas
fetchData(props){ function to call the api with server side pagination
if(props.previousPosition != 'above') { //an attempt to check if we passed that waypoint, do not call the api again
this.setState({page: this.state.page + 1}, function () { //increment the page number
this.getCatalogItems(this.state.categoryId, this.state.page) //make api call with incremented page number
.then((res) => {
console.log("fetched more data with scroll", res) //results
})
})
}else{
console.log("not calling fetch data")
}
}
这就是我调用航点的方式:
class ProductContainer extends React.Component {
constructor(props) {
super(props);
console.log("catalog product container initialized", this.props);
}
render() {
const {catalogProducts, getCatalogItems, renderWaypoint} = this.props;
console.log("props in roduct container", this.props)
return (
<div className="products-container">
{
catalogProducts && catalogProducts['products'] ?
catalogProducts['products'].map((product) => {
return (
<span>
HIIIIIIIIIIIIIIIIIIIIIIIIIII
<CatalogProduct product={product}/>
</span>
)
})
:
false
}
{renderWaypoint()}
########################################################################### way point here ################################################
</div>
);
}
}
ProductContainer.propTypes = {
catalogProducts: React.PropTypes.any.isRequired,
getCatalogItems: React.PropTypes.func.isRequired,
renderWaypoint: React.PropTypes.func.isRequired
};
export default ProductContainer;
我想做什么:
我有一个无限滚动目录页面。我希望在用户向下滚动到航点时进行api调用,如上面的组件中那样,我们已经渲染了从第一次api调用返回的产品,并希望再次往返服务器并进行渲染
答案 0 :(得分:0)
没有查看代码的任何代码......似乎你可以创建标志并在加载数据后将其设置为true,然后在加载数据之前检查该标志。也许不是最优雅的方式,但它会起作用。
class SomeClass extends React.Component {
constructor(props) {
super(props);
this.data = [];
this.fetched = [];
this._loadPageContent = this._loadPageContent.bind(this);
}
render(){
return (
<Waypoint
key={cursor}
onEnter={this._loadPageContent(this.props.pageId)}
/>
);
}
_loadPageContent(i) {
if(this.fetched.indexOf(i) <= -1){
//go get the data
this.data.push(someApiCall());
this.fetched.push(i);
}
}
}
export default SomeClass;