从API映射函数组件中的数组



我想调用并显示picker 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> 

)
}

相关内容

  • 没有找到相关文章

最新更新