React / Redux - 从API

时间:2017-03-14 21:04:26

标签: javascript reactjs redux

简而言之:我从具有X个对象的API中获取21个JSON对象,然后我想在用户向下滚动页面时从API获取接下来的21个对象。我没有运气就尝试了几个选项,我最后一个选择就是向这里的聪明开发人员提问。

我以前从未尝试过这个,所以如果有人会善待并展示一个提示/解决方案,从我的组件中做出一个例子,那将非常感激!

我尝试使用https://github.com/RealScout/redux-infinite-scroll,但我无法绕过它。

这是我的组件,我在componentDidMount上获取所有团队,然后从我的reducer中获取所有JSON对象:

    import React, { Component } from 'react'
    import { APIManager, DateUtils, YouTubeID } from '../../utils'
    import actions from '../../actions'
    import { connect } from 'react-redux'
    import  { Link, browserHistory } from 'react-router'


    class teams extends Component {
      constructor () {
        super()
        this.state = {

        }
      }

      selectTeam(team, event){
      event.preventDefault()
      this.props.selectTeam(team)
     }

      componentDidMount(){
        if(this.props.teams != null){
          return
        }
        this.props.fetchTeams()
      }

      componentDidUpdate(){
        if(this.props.teams != null){
          return
        }
        this.props.fetchTeams()
      }

      render(){
        return(
 <div className="scrollable-content-container">
 <ol className="portal-list-members debutants scrollable">

{(this.props.teams == null) ? null :
  this.props.teams.map((team, i) => {

    return (
      <li onClick={this.selectTeam.bind(this, team.teamname)} key={i} className="group">
        <h3>
        <Link to={'/team'} style={{color: '#444', textTransform: 'capitalize'}} className="url hoverable" href="#">
          <img style={{height: '160px', width: '160px'}} className="photo" src={"images/"+team.image}/>
        {team.teamname}
      </Link>
      </h3>
    </li>
    )
  })
}
</ol>
      </div>
        )
      }
    }

    const stateToProps = (state) => {
      return {
          teams: state.players.teams
      }
    }

    const dispatchToProps = (dispatch) => {
      return {
        selectTeam: (team) => dispatch(actions.selectTeam(team)),
        fetchTeams: (params) => dispatch(actions.fetchTeams(params))
      }
    }

    export default connect(stateToProps, dispatchToProps)(teams)

2 个答案:

答案 0 :(得分:5)

你可以看一下这篇文章:

使用React Waypoint进行无限和超越 - 使用React Waypoint进行无限滚动

使用react-waypoint的直接方法非常容易理解。

https://brigade.engineering/to-infinity-and-beyond-with-react-waypoint-cb5ba46a9150#.ftcyb9ynp

另外,您的参考号码还有一个:http://brigade.github.io/react-waypoint/#infinite-scroll

希望这会有所帮助:)

答案 1 :(得分:2)

我和这个问题的作者一样处于同样的境地。似乎业界的库通常不提供如何将此功能与Redux处理异步请求集成到API的完整示例。

因此我使用完整的客户端/服务器实现示例创建了一个完全相同的库。

您可以在此处找到图书馆:redux-lazy-scroll

您可以在此处找到Redux实施部分的示例:https://github.com/shotaK/redux-lazy-scroll/tree/master/dev/client/posts