javascript - 如何在 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={??}/>
解决方案
从状态中获取名称,假设 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)
}
推荐阅读
- wordpress - 通过自定义查询排除特色帖子不起作用
- lua - 如何通过 Lua Rocks 安装 lua 模块/库?
- c - 你能告诉我在使用 C 的哈希表的二次探测实现中这个 SEARCH 函数有什么问题吗?
- python - 如何将 ITEM 与数据库中的记录匹配?
- list - Prolog中列表中连续相似元素的子列表
- java - 我们可以通过更改 Java 中的返回类型(协变返回类型)来覆盖方法。为什么?
- python - loc 获取没有 .index[0] 的索引
- daml - IntelliJ 编辑器同步错误:find ./node_nix/bin: No such file or directory
- java - 在 POJO 类中为 JSON 映射定义必填字段
- mysql - 我是 SQL 新手,我无法从数据库中选择