首页 > 解决方案 > 如何在 React native 的 API url 中传递变量?

问题描述

我正在我的应用程序中构建一个搜索栏,并希望根据用户输入修改 URL。用户的输入是一个名字,即:'John'。在下面的这个函数中,我手动添加了一个名称进行测试。

我怎样才能使这个函数接受一个变量插入到 URL 中而不是“John”中,以便从TextInput

search功能 :

 search(){
    return fetch('http://10.0.2.2:3333/api/v0.0.5/search_user?q=John')
    .then((response) => response.json())
    .then((responseJson) => {
    this.setState({
    isLoading: false,
    userInfo: responseJson,
    });
    })
    .catch((error) =>{
    console.log(error);
    });
  }

文字输入:

<TextInput style = {styles.input} placeholder="Search for users" onChangeText={this.handleSearch} 
value={??}/>

标签: javascriptreactjsrestapireact-native

解决方案


从状态中获取名称,假设 handleSearch 将值保存为this.setState({ name: value}),使用模板字符串将该值添加到 url。

search = () => {
  return fetch(`http://10.0.2.2:3333/api/v0.0.5/search_user?q=${this.state.name}`)
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        isLoading: false,
        userInfo: responseJson,
      });
    })
    .catch(error => {
      console.log(error);
    });
}

输入的值将是来自状态的值,在 handleSearch 中设置。

<TextInput style = {styles.input} placeholder="Search for users" onChangeText{this.handleSearch} value={this.state.name}/>

handleSearch = (value) => {

 this.setState({ name: value}, this.search)
}

推荐阅读