我正在尝试使用react / react-redux在React中构建不定式滚动。这是我的容器组件:
import React from "react";
import {SingleArticleContainer} from "./singleArticleContainer";
import {connect} from "react-redux";
export class ArticleList extends React.Component{
componentDidMount(){
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event){
let scrollTop = event.srcElement.body.scrollTop;
let viewHeight=window.innerHeight;
let elemtScrollHeight=event.srcElement.body.scrollHeight;
if((elemtScrollHeight-scrollTop-viewHeight)<=20){
//load more article from server.
this.props.loadMoreArticles(); <--- got error because this.props is undefined
//HOW CAN I MAKE CALL HERE?
}
}
render(){
return <div>
{this.props.articles.map(()=>
<SingleArticleContainer/>
)}
</div>
}
}
const mapStateToProps=(state)=>{
return {
articles:state.articles
};
}
const mapDisptachToProps=(dispatch)=>{
return {
loadMoreArticles:()=>{
dispatch(loadArticles());
}
}
}我还为我的操作创建者loadArticles创建了操作创建者:
export function loadArticles(){
return {
type:"LOAD_ARTICLES"
};
}问:如何在handleScroll函数中调用loadMoreArticles?据我所知,loadMoreArticles现在是组件的一个属性。
发布于 2016-09-22 17:04:44
您必须绑定该函数,因为this不会在handleScroll中引用您的组件,而是引用window。这应该是可行的:
componentDidMount(){
this.scrollEvent = this.handleScroll.bind(this);
window.addEventListener('scroll', this.scrollEvent);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollEvent);
}发布于 2016-09-22 17:07:33
this.props未定义,因为您必须绑定该方法才能使用ES6语法访问this,没有自动绑定。例如,您可以使用this.handleScroll= this.handleScroll.bind(this)在构造函数上执行此操作。
发布于 2016-09-23 01:08:59
我猜你没有用connect包装你的组件,因为我看到了这一行:
export class ArticleList extends React.Component{您已经提到了容器组件,我猜您使用的是react-redux。
请修改如下并告诉我们结果(重点放在最后一行):
import React from "react";
import {SingleArticleContainer} from "./singleArticleContainer";
import {connect} from "react-redux";
class ArticleList extends React.Component{
componentDidMount(){
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event){
let scrollTop = event.srcElement.body.scrollTop;
let viewHeight=window.innerHeight;
let elemtScrollHeight=event.srcElement.body.scrollHeight;
if((elemtScrollHeight-scrollTop-viewHeight)<=20){
//load more article from server.
this.props.loadMoreArticles(); <--- got error because this.props is undefined
//HOW CAN I MAKE CALL HERE?
}
}
render(){
return <div>
{this.props.articles.map(()=>
<SingleArticleContainer/>
)}
</div>
}
}
const mapStateToProps=(state)=>{
return {
articles:state.articles
};
}
const mapDispatchToProps=(dispatch)=>{
return {
loadMoreArticles:()=>{
dispatch(loadArticles());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ArticleList)有关更多详细信息,请查看Redux文档:http://redux.js.org/docs/basics/UsageWithReact.html#presentational-and-container-components
https://stackoverflow.com/questions/39634557
复制相似问题