[英]React-Native how can i return my json data to my prop?
I have a component and that component should send a json url to my function.我有一个组件,该组件应该将 json url 发送到我的 function。 Then that function will fetch it and send back it as props so i can see data in props.
然后 function 将获取它并将其作为道具发回,这样我就可以在道具中看到数据。 But even i take data true, when i return it its not going well its always give me that error:
但即使我认为数据是真的,当我返回它时它并不顺利它总是给我那个错误:
{"dataSource": {"_U": 0, "_V": 0, "_W": null, "_X": null}
My component:我的组件:
const DropdownComponent = props => {
console.log('props -->',props)
return (
<Picker
dataSource={props.dataSource}
mode="dropdown"
dropdownIconColor="white"
style={styles.touchstyle}
onValueChange={props.onChange()}>
{/* {props.dataSource &&
props.dataSource.map(data => {
return (
<Picker.Item
color="black"
key={data.id}
label={data.name}
value={data.id}
/>
);
})} */}
</Picker>
);
};
My component in app:我在应用程序中的组件:
<DropdownComponent
key="1"
dataSource={getData( // I need send that url and type and when its fetcher fetch url it should return back data to dataSource
'https://api.npoint.io/995de746afde6410e3bd',
'city',
)}
onChange={onChange}
/>
My Fetcher:我的提取器:
const getData = (apiUrl, type) => {
return apiService.getPost(apiUrl,type).then(cz=>{
console.log('cz--->',cz) // cz is show me my datas when i check console
return cz;
})
My Api Service:我的 Api 服务:
apiService.getPost = async function (url, params) {
const x = fetch(url).then(res => res.json())
return x;
Result on log: https://ibb.co/k5VdN8z ( Also i dont know why props shows before than my function too )日志结果: https://ibb.co/k5VdN8z (我也不知道为什么道具比我的 function 更早显示)
Thanks for reply!谢谢您的回复!
That's because you're passing a Promise
in dataSource
, you should declare a state in the dropdownlist, that state should be updated when the dataSource
resolves:那是因为你在
dataSource
中传递了一个Promise
,你应该在下拉列表中声明一个 state ,当dataSource
源解析时应该更新 state :
const DropdownComponent = props => {
const [data, setData] = useState([]);
useEffect(() => {
props.dataSource.then(setData);
}, [props.dataSource]);
return (
<Picker
dataSource={props.dataSource}
mode="dropdown"
dropdownIconColor="white"
style={styles.touchstyle}
onValueChange={props.onChange()}>
{data.map(data => {
return (
<Picker.Item
color="black"
key={data.id}
label={data.name}
value={data.id}
/>
);
})}
</Picker>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.