单击按钮后如何从api获取数据

时间:2019-04-23 18:55:17

标签: api react-native

我尝试在React Native中从api获取数据。我使用提取。 我的构造函数:

constructor(props) {
 super(props);

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

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

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> 

1 个答案:

答案 0 :(得分:0)

按下搜索按钮后,将要从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>