反应组件属性

时间:2018-02-06 01:47:32

标签: javascript reactjs react-native

我尝试使用组件属性 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>
    )
  }
}

1 个答案:

答案 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