gpt4 book ai didi

javascript - react 组件属性

转载 作者:行者123 更新时间:2023-12-03 02:33:29 25 4
gpt4 key购买 nike

我正在尝试使用组件属性this.albumButtons来存储AlbumButtons数组。

componentDidMount被调用时,我获取专辑名称并将其设置为状态。然后,我从名称中调用 makeButtons。

在 makeButtons 函数中,我将 this.albumButtons 设置为 AlbumButton 组件的数组。

当我检查 this.albumButtons 长度时,我得到 0。

我做错了什么?

export default class ModalContent extends Component {
constructor(props){
super(props);
this.state = {
albumNames: [],
isLoading: false,
isEmptyOfAlbums: false,
}
this.albumButtons = []
}

componentDidMount(){
this.setState({isLoading: true})
const getAlbumsNamesPromise = new Promise ((resolve, reject) => {
MySwiftClass.getAlbumsNames((arr) => {
if(arr.length === 0) this.setState({isEmptyOfAlbums: true});
this.setState({albumNames: arr})
})
})
getAlbumsNamesPromise.then(this.makeButtons).then(this.setState({isLoading: false}))
}

makeButtons() {
//const component = this;

return new Promise((resolve, reject) => {
this.albumButtons = this.state.names.map((name) =>
<AlbumButton
key={name}
name={name}
/>
)
resolve()
})
}

render() {
if (this.state.isLoading){
return(
//loading screen
)
}
return(
<Text>{this.albumButtons.length}</Text>
)
}
}

最佳答案

setState 是异步的,您需要在 setState 的回调中resolve,以便它等待状态更新为 albumNames:

const getAlbumsNamesPromise = new Promise ((resolve, reject) => {
MySwiftClass.getAlbumsNames((arr) => {
if(arr.length === 0) this.setState({isEmptyOfAlbums: true});
this.setState({albumNames: arr}, resolve)
})
}) // also need to pass a function into .then, not invoke a function
getAlbumsNamesPromise.then(this.makeButtons).then(() => this.setState({isLoading: false}))

您还映射了 this.state.names.map 我认为您的意思是 this.state.albumNames.map

关于javascript - react 组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634259/

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