[英]Shows empty data using rn picker select in react native
const [country, setCountry] = useState([]);
useEffect(() => {
DataService.get(API.API_GET_COUNTRY).then((response) => {
console.log('Countries', country);
// let data = response.data.items;
// data.map(names=>{console.log("name",names['name'])
// let piker=[]
// piker.push({label:names['name'],value:names['id']})
// console.log("Picker",piker);
// })
setCountry([response.data.items]);
});
}, []);
function getPickerItems(array, labelKey, valueKey) {
const pickerItems = [];
array &&
array.map((item) =>
pickerItems.push({ label: item[labelKey], value: item[valueKey] })
);
return pickerItems;
}
<RNPickerSelect items={getPickerItems(country, 'name', 'id')}/>
// I was trying to show the list of countries name in picker select. // 我试图在选择器选择中显示国家名称列表。 I get response from the api and set in the country state.我从 api 得到响应并设置在国家/地区。 Since that i get array of data.从那以后我得到了数据数组。 But i am not able to see data in picker.但我无法在选择器中看到数据。 Please help me out to solve this problem.请帮我解决这个问题。
The way you code is written, each time a component is rerendered getPickerItems
function once again has to go over list of countries fetched from server to format it according your needs.根据您编写代码的方式,每次重新渲染组件时, getPickerItems
函数都必须再次检查从服务器获取的国家/地区列表,以根据您的需要对其进行格式化。 But you actually don't need this, if you adjust your state so that it closely follows the view model (used by RNPickerSelect):但是你实际上并不需要这个,如果你调整你的状态以使其紧密跟随视图模型(由 RNPickerSelect 使用):
const [countries, setCountries] = useState([]);
useEffect(() => {
DataService.get(API.API_GET_COUNTRY).then((response) => {
const fetchedCountries = response.data.items.map(item => {
return {
label: item.name,
value: item.id
};
});
setCountries(fetchedCountries);
});
}, []);
... and then just pass this state into RNPickerSelect: ...然后将此状态传递给RNPickerSelect:
<RNPickerSelect items={countries} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.