我正在尝试使用React / react-redux构建不定式滚动。这是我的容器组件:
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"
};
}
问题:如何在loadMoreArticles
函数内调用handleScroll
?据我所知,loadMoreArticles
现在是组件的属性。
答案 0 :(得分:0)
您必须绑定该功能,因为this
不会在handleScroll
中引用您的组件,而是引用window
。这应该有效:
componentDidMount(){
this.scrollEvent = this.handleScroll.bind(this);
window.addEventListener('scroll', this.scrollEvent);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollEvent);
}
答案 1 :(得分:0)
this.props
未定义,因为您必须使用ES6语法绑定方法以访问this
,没有自动绑定。例如,您可以使用this.handleScroll= this.handleScroll.bind(this)
。
答案 2 :(得分:0)
我猜你没有用连接包装你的组件,因为我看过这行:
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