gpt4 book ai didi

javascript - 让辅助方法在状态初始更新时运行

转载 作者:行者123 更新时间:2023-11-30 19:26:50 26 4
gpt4 key购买 nike

我的目标是让 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.. 当您在 props 中获取数据时运行该函数并将变量设置为 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
}
}
}

关于javascript - 让辅助方法在状态初始更新时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com