【问题标题】:Can't access json values in react native无法在本机反应中访问 json 值
【发布时间】:2022-01-21 05:58:33
【问题描述】:

我最近一直在使用 React-native(老实说,这是我第一次)。

我正在从 api 中检索值,并尝试在 Text 标记中显示它们。但我不知道如何访问这些值。

所以,这是我的代码:

export const Home = () => {
  
  const [data, setData] = useState([]);

  const getApiInformations = async () => {

    const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita');
    const responseJson = await response.json();
    setData(responseJson);
  }
  
  useEffect(() => {
    getApiInformations();
  }, []);
  
  return (
    <View>
        <Text>
            {
              I want to put the values here like : data.idDrink, data.OtherValue,...
            }
        </Text>
    </View>
  );
}

在 {data.drinks} 我有:

0: {idDrink: '11007', strDrink: 'Margarita', strDrinkAlternate: null, strTags: 'IBA,ContemporaryClassic', strVideo: null, …}
1: {idDrink: '11118', strDrink: 'Blue Margarita', strDrinkAlternate: null, strTags: null, strVideo: null, …}
2: {idDrink: '17216', strDrink: "Tommy's Margarita", strDrinkAlternate: null, strTags: 'IBA,NewEra', strVideo: null, …}
3: {idDrink: '16158', strDrink: 'Whitecap Margarita', strDrinkAlternate: null, strTags: null, strVideo: null, …}
4: {idDrink: '12322', strDrink: 'Strawberry Margarita', strDrinkAlternate: null, strTags: null, strVideo: null, …}
5: {idDrink: '178332', strDrink: 'Smashed Watermelon Margarita'

感谢您的帮助:)。

【问题讨论】:

    标签: json react-native


    【解决方案1】:

    您可以在 javascript 中使用.map() 功能。例如:

    {data && data.map((element) => {
        return <Text key={element.idDrink}>ID: {element.idDrink} Name: {element.strDrink}</Text>
    })}
    

    【讨论】:

    • 几点建议:1. 状态是data,而不是responseJson,2. 不要忘记每个&lt;Text&gt; 上的key 属性。
    • 谢谢。进行了这些更改。
    • 我按照你说的做了,但是我得到了那个错误:typeerror: cannot read properties of undefined (reading 'map') because before doing data.map我必须做data.drinks.map。但是如果 data.map 完全像你我有这个错误: typeerror : data.map is not a function.
    • 你能console.log(responseJson) 显示吗?
    • 当我执行 console.log(responseJson) 时,首先我有一个像这样的空数组:[],然后我自动有一个像这样的第二行:{drinks: Array(6)}(它是由于 useEffect() 我想)
    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2021-06-28
    • 2021-11-07
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多