如何提高axios的速度?

时间:2019-01-07 21:16:47

标签: reactjs http django-rest-framework react-redux axios

因为我刚开始使用axios,所以通常在使用它时会遇到麻烦。具体来说,我现在正在制作react-infinite-scroll功能,但是当我将它与其他网站的速度进行比较时,我的帖子(react-infinite-scroll功能)将会慢慢显示。那我想这个问题是由两个原因造成的
1.我没有正确使用axios
2.有件事使axios的速度加快,但我没有使用它
这是我的代码,请给我一些建议以提高我的http请求速度。

感谢您阅读我的问题!

class MainPage extends Component {

    constructor(props) {
        super(props)
        axios.get("http://127.0.0.1:8000/api/question")
        .then(res => {
            this.setState({
                AnswerPostMultiList: res.data
            })
          }
        )
        .catch(err => {
            console.log(err)
        })
    }

    state = {
        AnswerPostMultiList : []
    }

    componentDidMount() {
        window.addEventListener("scroll", this.handleScroll);
    }

    componentWillUnmount() {
        window.removeEventListener("scroll", this.handleScroll);
    }

    handleScroll = () => {

        console.log("scroll is executing")

        const { innerHeight } = window;
        const { scrollHeight } = document.body;

        const scrollTop =
          (document.documentElement && document.documentElement.scrollTop) ||
          document.body.scrollTop;

        if (scrollHeight - innerHeight - scrollTop < 1000 && !this.props.isLoading["isLoading"]) {
          this.props.onIsLoading() #To prevent this code from calling back continuously, change the value of this.props.isLoading["isLoading"] to false 

              axios.get("http://127.0.0.1:8000/api/question")
              .then(res => {

              this.setState({
                  AnswerPostMultiList: this.state.AnswerPostMultiList.concat(res.data)
              })
              this.props.onIsLoading() #change the value of this.props.isLoading["isLoading"] to true 
            }
          )
          .catch(err => {
              console.log(err)
          })
        }
      };

    render() {
        return(
            <>

                <PageHeader />
                <div className="find_members">
                { this.state.AnswerPostMultiList.map((answerpost,index) => {
                    return <AnswerPostMulti question={answerpost.question_text} q_owner={answerpost.question_owner} answer={answerpost.answer_image} a_owner={answerpost.answer_owner} key={index} />
                  })
                }
                </div>

            </>
        )
    }
}



const mapDispatchToProps = (dispatch) => ({
    onIsLoading: () => {
        dispatch(isLoadingActions.isLoading())
    }
  })

  const mapStateToProps = state => ({
      isLoading: state.isLoading
  })


export default connect(mapStateToProps, mapDispatchToProps)(MainPage)

1 个答案:

答案 0 :(得分:1)

调用 axios API 的最佳位置是 componentDidMount(){} 。 应用程序加载过程将按此顺序依次调用skeleton-> Initial rendering-> later componentDidMount方法。因此,这里将加载您的应用程序框架,然后您可以获取数据并将其用于您的应用程序框架。

type
相关问题