javascript - 获取帮助方法以在初始状态更新时运行
问题描述
我的目标是让 autoPagination 函数在 this.props.userSaves 最初更新状态时运行。在我的程序中,它一开始是一个空数组,在初始化时,数组中存储了 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);
解决方案
取一个变量并最初将其设置为 true。当您在道具中获取数据时运行该函数并将变量设置为 false,以便它不会再次运行。
constructor (props)
{
super(props)
this.myvar = true
}
componentWillRecieveProps(nextProps)
{
if(this.myvar)
{
if(check if get your data)
{
// run your function
this.myvar= false
}
}
}
推荐阅读
- python - 查看dataflow中安装了哪些非python包
- java - 无法在对话活动中显示收到或发送的即时消息 - android
- node.js - Node.js 在使用 --watch 构建 Angular 6 期间崩溃
- c# - 转换 JSON ToList 并将其解析为 EF 模型
- c# - 如何将 IConfigurationSection 中的配置映射到一个简单的类
- python - 围绕另一个点旋转一组 2D 点
- java - 以给定角度旋转一个点
- python-3.x - 匹配模式后向文件添加新行 - Python
- javascript - 错误:预计没有打开的请求,发现 1 (Angular)
- jquery - 使用 jQuery 数据属性在伪元素的内容中插入新行