如何使用ReactJS原生功能组件呈现从Cloud Firestore检索到的数据?
我想做这样的事情:
const result=[]
db.collection("collection").where("parameter", "==", "value")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
result.push(doc.data());
});
export default function foo(){
return(
<View>
{result.map((item) =>
<CustomComponent data=item />
)}
</View>
)
}显然,代码无法工作,因为渲染发生在promise解析之前。我在网上读了很多书。一种可能的解决方案是更新ComponentDidMount中的状态,其中发生对db的请求。
所以我的问题是,我怎样才能用一个功能组件做到这一点呢?这是唯一的最好的解决方案吗?我想要从Firestore检索的数据和我想要显示的数据不会变化得那么快。
发布于 2020-11-23 17:46:56
她的是一个代码片段,希望它能为你工作...
const useData = () => {
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
const getData = () => {
const data = [];
db.collection('collection')
.where('parameter', '==', 'value')
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
data.push(doc.data());
});
setList(data);
});
};
return [loading, list, getData];
};
export default function App() {
const [loading, list, getData] = useData();
useEffect(() => {
getData();
}, []);
return (
<View style={styles.container}>
{loading ? (
<ActivityIndicator />
) : (
{
// renderList
}
)}
</View>
);
}发布于 2020-11-24 20:30:11
这可能是因为您正在尝试呈现一个数据数组。我建议看看这个很好的例子here。我添加了一些ReactJS映射的示例,您可能会发现它们对您有帮助:
render() {
return (<div>
{this.state.people.map((person, index) => (
<p key={index}>Hello, {person.name} from {person.country}!</p>
))}
</div>);
}this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})您可能会发现这些教程和用户指南很有帮助:
https://stackoverflow.com/questions/64965756
复制相似问题