[英]React Native -Flatlist renderItem promise
I have a working flatlist in react native我有一个反应原生的工作平面列表
<FlatList
data={orders}
keyExtractor={item => item._id}
renderItem={({ item }) => (renderItem(item))}
/>
I've added a new promise withing my renderItem function like :我在 renderItem 函数中添加了一个新的承诺,例如:
const renderItem = (item) => {
const getRestaurant = async (id) => {
uri = 'https://xxx.xxx.xxx/api/list/xxx/' + id ;
return fetch(uri)
.then((response) => response.json())
.then((json) => {
return json;
//console.log("json=>"+json[0].name);
})
.catch((error) => {
console.error(error);
});
}
const promise = getRestaurant(item.restaurantId);
promise.then(data =>{
console.log(data[0].name)
return (
<Text>{data[0].name}</Text>
)
})}
If I do a如果我做一个
console.log(data[0].name)
the information i am looking for is correct but i simply cannot return that information in my flatlist to be displayed .我正在寻找的信息是正确的,但我根本无法在要显示的平面列表中返回该信息。 Ive done something like :
我做过类似的事情:
return (
<Text>{data[0].name}</Text>
)
but nothing is being display on my flatlist !但我的平面列表上没有显示任何内容!
Can anyone please help me .谁能帮帮我吗 。 Thank you
谢谢
You cannot use the variables directly inside the component , you need to use state.您不能直接在组件内部使用变量,您需要使用状态。
Because when there is a change in state , react-native will render your components.因为当 state 发生变化时, react-native 会渲染你的组件。
For example you can make use of useState hook例如,您可以使用 useState 钩子
first import useState from like below首先从下面导入 useState
import React, { useState } from "react"; import React, { useState } from "react";
and then inside ur function然后在你的函数里面
const [response, setResponse] = React.useState(false);
and then inside ur promise然后在你的承诺里面
promise.then(data =>{
setResponse(data[0].name)
return (
<Text>{response}</Text>
)
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.