我尝试使用组件属性 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>
)
}
}
答案 0 :(得分:1)
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