【问题标题】:React-native: setstate for the listview but object still return undefinedReact-native:为列表视图设置状态,但对象仍返回未定义
【发布时间】:2018-09-25 05:52:22
【问题描述】:

从下面的代码中,我尝试让数据源返回一个字符串,但它返回未定义

constructor(props) {
    super(props)
    this.state = {
        uuid : this.props.navigation.state.params.uuid,
        facilityData: [],
        dataSource : []
    };
}

componentDidMount() {
    facilityStore.getFacilityInfo(this.state.uuid)
        .then((res) => {
            this.setState({
                facilityData: res.data.data
            })
            {this.checkparticipants()}
        })
        .catch((error) =>{
            alert(error);
        })
};

checkparticipants(){
    var ds = new ListView.DataSource({rowHasChanged: (r1,r2) => r1!=r2});
    this.setState({
        dataSource : ds.cloneWithRows([
            {invitePlaceholder : "Participant"},
            {invitePlaceholder : "Participant"},
            {invitePlaceholder : "Participant"},
            {invitePlaceholder : "Participant"},
        ])
    })
    console.log(this.state.dataSource.invitePlaceholder)
}

我想根据列表视图的数量来渲染文本输入,但是有一个错误是:

TypeError: undefined is not an object

<ListView
    dataSource = {this.state.dataSource}
    renderRow={(rowData)=>
        <TextInput style={styles.input}
            placeholder={rowData.invitePlaceholder}
        />
    }
/>

那么我应该怎么做才能使对象不从代码中未定义?

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    setState 是一种异步方法。所以,为了让任何东西处于状态,我认为你需要在状态设置后执行checkParticipants。这是作为setState的回调完成的:

    facilityStore.getFacilityInfo(this.state.uuid)
    .then((res) => {
      this.setState({ facilityData: res.data.data }, this.checkparticipants)
    })
    

    【讨论】:

      【解决方案2】:
      this.checkparticipants()
      

      未被调用,因为您的语法错误。 你的 componentDidMount 生命周期应该是:

      componentDidMount() {
          facilityStore.getFacilityInfo(this.state.uuid)
              .then((res) => {
                  this.setState({
                      facilityData: res.data.data
                  },
                  () => this.checkparticipants());
              })
              .catch((error) =>{
                  alert(error);
              });
      }
      

      setState 是一种异步方法。设置完状态后调用checkparticipants()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-30
        • 2021-12-07
        • 2020-09-26
        • 2021-08-06
        • 1970-01-01
        • 2017-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多