从 API 映射功能组件中的数组

Map an array in functional component from API

我想在选择器 React Native 中调用并显示 API。我不明白如何在地图部分的功能组件中做到这一点,以便它获得价值

import React, {useState,useEffect} from 'react';
import {View, StyleSheet, Picker} from 'react-native';

const App = () => {

    const [selectedValue, setSelectedValue] = useState([]);

    useEffect(() => {
        fetch('https://aboutreact.herokuapp.com/demosearchables.php')
        .then(response => response.json())
        .then(responseJson => {
            console.log(responseJson.results)
            setSelectedValue(responseJson.results)
        })
        .catch((error) => {
            console.error(error);
          });
      }, []);

    return (        
        <View style={{flex: 1,backgroundColor:'white'}}>
                <Picker
                    selectedValue={selectedValue.id}
                    style={{ width: '100%' }}
                    onValueChange={(itemValue) => setSelectedValue({ id: itemValue })}>
                    { ???.map((selectedValue, i) => {
                        return <Picker.Item key={i} value={selectedValue.id} label={selectedValue.name} />
                    })}
                </Picker>
               </View> 
        
    )
}

export default App
  1. 使用数组存储 Picker 的初始值。
  2. 然后,在解析 API 时在该数组上设置状态。
  3. 使用另一个状态来存储所选值。
import React, {useState,useEffect} from 'react';
import {View, StyleSheet, Picker} from 'react-native';

const App = () => {
    const [values, setValues] = React.useState([]);
    const [selectedValue, setSelectedValue] = useState(null);

    useEffect(() => {
        fetch('https://aboutreact.herokuapp.com/demosearchables.php')
        .then(response => response.json())
        .then(responseJson => {
            setValues(responseJson.results)
        })
        .catch((error) => {
            console.error(error);
          });
      }, []);

    return (        
        <View style={{flex: 1,backgroundColor:'white'}}>
                <Picker
                    selectedValue={selectedValue ? selectedValue.id : null}
                    style={{ width: '100%' }}
                    onValueChange={(itemValue) => setSelectedValue({ id: itemValue })}>
                    { values.map((value, i) => {
                        return <Picker.Item key={i} value={value.id} label={value.name} />
                    })}
                </Picker>
               </View> 
        
    )
}