[英]How to display json data on screen based on user input expo react-native
我有一些從 api 獲取的 json 數據,並根據用戶輸入顯示在 iOS 模擬器上。
屏幕頂部有一個搜索欄,用戶可以在其中鍵入任何符號值,並且應該在屏幕上顯示該特定值。
我的 json 數據:
Object {
"name": "Chesapeake Energy",
"symbol": "CHK",
},
Object {
"name": "C. H. Robinson Worldwide",
"symbol": "CHRW",
},
因此,如果用戶鍵入 CHK,它應該顯示符號和名稱,如下所示:
CHK
Chesapeake Energy
我的代碼:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
View,
TouchableWithoutFeedback,
Keyboard,
FlatList,
TextInput,
Button,
Text,
} from "react-native";
import { useStocksContext } from "../contexts/StocksContext";
import { scaleSize } from "../constants/Layout";
import { Ionicons } from "@expo/vector-icons";
import { ListItem } from "react-native";
export default function SearchScreen({ navigation }) {
const { ServerURL, addToWatchlist } = useStocksContext();
const [state, setState] = useState({
/* initial state here */
myListData: [],
search: "",
});
useEffect(() => {
renderWithData();
}, []);
renderWithData = () => {
return fetch("http://131.181.190.87:3001/all")
.then((res) => res.json())
.then((json) => {
setState({
isLoaded: true,
myListData: json,
});
setTimeout(() => {
console.log(json);
}, 1000);
});
};
let onChangeText = (event) => {
setState({ search: event }); //here it does not set the value of event(userinput) to search
};
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.container}>
<TextInput
style={styles.textinput}
placeholder="Search here"
placeholderTextColor="white"
onChangeText={(search) => onChangeText(search)}
/>
</View>
</TouchableWithoutFeedback>
);
}
我的問題是如何編寫 onChangeText() 以便可以根據用戶輸入在屏幕上顯示符號和名稱。
let onChangeText = (event) => {
setState({ search: event }); //here it does not set the value of event(userinput) to search
};
在這里,我試圖將用戶值(事件)設置為search
,但它沒有設置值,但如果我打印event
,我可以在控制台中看到任何用戶類型。 如何根據用戶類型顯示符號和名稱? 有沒有辦法過濾這些?
是的。 javascript中有一個filter
功能。
首先,您必須將 JSON 用戶列表存儲在 state 或某處,例如
userlist: []
然后你的onChangeText
onChangeText = {(event) => { let result = userlist.filter((item) => { return item.symbol === event }); // result is an array contains your users that have symbol in your input. // Handle your result. }}
你可以在這里找到更多:
https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
那它。 希望有所幫助。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.