gpt4 book ai didi

javascript - 如何在React Native中获取选定的元素?

转载 作者:行者123 更新时间:2023-12-02 21:32:11 25 4
gpt4 key购买 nike

我在 FlasList 中列出了用户,每个用户旁边都有一个按钮。按下此按钮时,它会触发一个名为 following 的函数,该函数将请求 URL 发送到 API 端点 (following),以检索所选用户的以下用户。

在此 URL 请求中,应包含所选的 user_id,如下所示:http://example/api/user_id/following'。因此,只有 user_id 会根据所选用户更改每个请求

现在我正在努力解决如何获取所选用户?任何对此的想法或建议将不胜感激

以下功能:

following(){
return fetch(`http://example/api/${user_id}/following`)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
content: responseJson,
});
})
.catch((error) =>{
console.log(error);
});
}

渲染:

<View style={{ flex: 1 }}>
<FlatList
data={this.state.content}
renderItem={({ item }) => (
<View style={{ flexDirection: "row", flex: 1 }}>
<Text>
{" "}
{item.user.given_name +
" " +
item.user.family_name +
"\n" +
item.content}
</Text>
<TouchableOpacity
style={styles.button}
onPress={() => this.following(item.user.user_id)}
>
<Text>Following</Text>
</TouchableOpacity>

<TouchableOpacity
style={styles.button}
onPress={() => this.following()}
>
<Text>Followers</Text>
</TouchableOpacity>
</View>
)}
keyExtractor={({ id }, index) => id}
/>
</View>;

最佳答案

您是否尝试过类似的方法,将 user_id 作为函数的参数传递,然后使用模板文字将其插入到 url 中?

以下功能:

following(id){
return fetch(`http://example/api/${user_id}/following`)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
content: responseJson,
});
})
.catch((error) =>{
console.log(error);
});
}

渲染:

<View style={{ flex: 1 }}>
<FlatList
data={this.state.content}
renderItem={({ item }) => (
<View style={{ flexDirection: "row", flex: 1 }}>
<Text>
{" "}
{item.user.given_name +
" " +
item.user.family_name +
"\n" +
item.content}
</Text>
<TouchableOpacity
style={styles.button}
onPress={() => this.following(item.user_id)}
>
<Text>Following</Text>
</TouchableOpacity>

<TouchableOpacity
style={styles.button}
onPress={() => this.following(item.user_id)}
>
<Text>Followers</Text>
</TouchableOpacity>
</View>
)}
keyExtractor={({ id }, index) => id}
/>
</View>;

关于javascript - 如何在React Native中获取选定的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60593580/

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