gpt4 book ai didi

javascript - 如何在 React Native 中的 API url 中传递变量?

转载 作者:行者123 更新时间:2023-11-28 03:07:40 25 4
gpt4 key购买 nike

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

如何才能让该函数在 URL 中插入一个变量而不是“John”,以从 TextInput 获取用户的输入

搜索功能:

 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={??}/>

最佳答案

从state中获取名称,假设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)
}

关于javascript - 如何在 React Native 中的 API url 中传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60467314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com