使助手方法在状态的初始更新上运行

时间:2019-06-29 04:58:17

标签: javascript reactjs redux

我的目标是让this.props.userSaves最初处于状态更新时运行autoPagination函数。在我的程序中,它以一个空数组开始,并在初始化时在该数组中存储了100个对象。问题在于autoPagination在存储对象之前就在运行,因此while循环没有在运行。我已经使用setTimeout修复了此问题,但我并不认为这是一个长期解决方案。有什么想法吗?

以下代码嵌套在基于类的组件中。

  autoPagination = async token => {
    while (this.props.userSaves.length > 0) {
      const { userSaves } = this.props
      const lastPage = userSaves[userSaves.length-1].data.name

      const userSavesObject = await axios.get (`https://oauth.reddit.com/user/${this.props.username}/saved/.json?limit=100&after=${lastPage}`, {
      headers: { 'Authorization': `bearer ${token}` }
    })
      const currentPageSaves = userSavesObject.data.data.children
      this.props.storeUserHistory(currentPageSaves)
      this.props.appendUserHistory(currentPageSaves)
    }
  }

完整组件(已请求):

import axios from 'axios';
import React from 'react';
import { connect } from 'react-redux';
import { storeUserHistory, appendUserHistory, storeInitialData } from '../actions/index.js'

class ListSaved extends React.Component {
  componentDidMount (props) {
    const params = new URLSearchParams(this.props.location.hash);
    const token = params.get('#access_token')
    this.props.storeInitialData(token)

    setTimeout(() => {
      this.autoPagination(token);
    }, 3000)
  }

  autoPagination = async token => {
    while (this.props.userSaves.length > 0) {
      const { userSaves } = this.props
      const lastPage = userSaves[userSaves.length-1].data.name

      const userSavesObject = await axios.get (`https://oauth.reddit.com/user/${this.props.username}/saved/.json?limit=100&after=${lastPage}`, {
      headers: { 'Authorization': `bearer ${token}` }
    })
      const currentPageSaves = userSavesObject.data.data.children
      this.props.storeUserHistory(currentPageSaves)
      this.props.appendUserHistory(currentPageSaves)
    }
  }

  renderPostTitles = () => {
    return this.props.totalSaves.map((saved) => {
      return (
        <div key={saved.data.id}>
          <div>{saved.data.title}</div>
        </div>
      )
    })
  }

  render () {
    return <div>{this.renderPostTitles()}</div>
  }
}

const mapStateToProps = state => {
  console.log(state)
  return { 
    username: state.username,
    userSaves: state.userHistory,
    totalSaves: state.totalUserHistory
   }
}

export default connect(mapStateToProps, { storeUserHistory, appendUserHistory, storeInitialData })(ListSaved);

2 个答案:

答案 0 :(得分:0)

接受一个变量并将其初始设置为true。在道具中获取数据时运行该函数,并将变量设置为false,以使其不再运行。.

 try {
        final File localFile = File.createTempFile("images", "jpg");
        storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                mImageView.setImageBitmap(bitmap);

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
            }
        });
    } catch (IOException e ) {}

答案 1 :(得分:0)

更正的组件。每次组件更新时,都会运行该功能。安装后立即更新组件

import axios from 'axios';
import React from 'react';
import { connect } from 'react-redux';
import { storeUserHistory, appendUserHistory, storeInitialData } from '../actions/index.js'

class ListSaved extends React.Component {
  componentDidMount (props) {
    const params = new URLSearchParams(this.props.location.hash);
    const token = params.get('#access_token')
    this.props.storeInitialData(token)
  }
  
  componentDidUpdate (props) {
    this.autoPagination(token);
  }

  autoPagination = async token => {
    while (this.props.userSaves.length > 0) {
      const { userSaves } = this.props
      const lastPage = userSaves[userSaves.length-1].data.name

      const userSavesObject = await axios.get (`https://oauth.reddit.com/user/${this.props.username}/saved/.json?limit=100&after=${lastPage}`, {
      headers: { 'Authorization': `bearer ${token}` }
    })
      const currentPageSaves = userSavesObject.data.data.children
      this.props.storeUserHistory(currentPageSaves)
      this.props.appendUserHistory(currentPageSaves)
    }
  }

  renderPostTitles = () => {
    return this.props.totalSaves.map((saved) => {
      return (
        <div key={saved.data.id}>
          <div>{saved.data.title}</div>
        </div>
      )
    })
  }

  render () {
    return <div>{this.renderPostTitles()}</div>
  }
}

const mapStateToProps = state => {
  console.log(state)
  return { 
    username: state.username,
    userSaves: state.userHistory,
    totalSaves: state.totalUserHistory
   }
}

export default connect(mapStateToProps, { storeUserHistory, appendUserHistory, storeInitialData })(ListSaved);