【问题标题】:how to get data from api after click button单击按钮后如何从api获取数据
【发布时间】:2019-04-23 18:55:17
【问题描述】:

我尝试在 react native 中从 api 获取数据。我使用获取。 我的构造函数:

constructor(props) {
 super(props);

 this.state = {
   firstName: "",
   lastName:"",
   loading: true,
   dataSource:[],
  };
}

通过 fetch 获取数据但不起作用:

componentDidMount(){
fetch("http://myurl.com/api/person?name="+this.state.firstName+"&last_name="+this.state.lastName)
.then(response => response.json())
.then((responseJson)=> {
  this.setState({
   loading: false,
   dataSource: responseJson.data
  })
})
.catch(error=>console.log(error))
}

我还有 2 个用于名字/姓氏的文本输入和一个按钮,我想在单击按钮后从 api 获取数据,现在我使用 setState

  <Item stackedLabel>
    <Label>First Name</Label>
    <Input name="firstName" onChangeText={(firstName)=>{this.setState({firstName: firstName});}} />
  </Item>
  <Item stackedLabel Last>
    <Label>Last Name</Label>
    <Input name="lastName" onChangeText={(lastName)=>{this.setState({lastName: lastName});}} />
  </Item>
  <Button style={styles.SearchButton} full><Text> Search Person </Text> 

【问题讨论】:

  • 请您再解释一下。你真正想要什么?
  • 当我在输入字段中输入名字和姓氏并单击搜索按钮时,我想从 api 获取包含这个名字和姓氏的数据

标签: api react-native


【解决方案1】:

按下搜索按钮时,调用将从 api 获取数据的方法并从 componentDidMount 中删除 api 调用代码。

_onPressButton() {
    fetch("http://myurl.com/api/person?name="+this.state.firstName+"&last_name="+this.state.lastName)
    .then(response => response.json())
    .then((responseJson)=> {
      this.setState({
       loading: false,
       dataSource: responseJson.data
      })
    })
    .catch(error=>console.log(error))
  }

<Button style={styles.SearchButton} onPress={() => this._onPressButton() } full><Text> Search Person </Text> 

【讨论】:

  • 您面临的问题是什么?
  • 当我尝试 onPress={this._onPressButton} 时没有显示,但是当我每次循环尝试 onPress={this._onPressButton() } 时
  • 您没有将 _onPressButton 绑定到此,因此存在问题。您可以使用 onPress={() =&gt; this._onPressButton() } 之类的箭头函数来解决此问题。
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2019-11-30
  • 2020-12-17
相关资源
最近更新 更多