React:如何访问对象和显示值



我正在使用React Hooks创建一个简单的博客。到目前为止,我成功地从数据库中获取了数据,并且我可以用props.articles控制台记录所有数据。然而,如果我写props.articles.title,它会说"未定义"。如何显示与从父组件获得的ID匹配的对象的标题和文本?

The data of blog posts
[
{
"id": "1oQAPxRl2k7Spev10qFE",
"text": "Looooorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostr.",
"title": "Title#1"
},
{
"id": "ThRwQIgpLUB7iBq1H8VI",
"text": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.",
"title": "Title#2"
},
{
"id": "aJvajhmoCXbfU7RJVkzn",
"text": "Nuncccc sit amet ante convallis, semper metus ut, ornare leo. Fusce tellus metus, commodo at massa non, auctor pharetra ipsum. Maecenas in suscipit nulla. Nam in consectetur dui, non laoreet purus. Aliquam erat volutpat. Etiam non risus vestibulum, ornare mauris ut, pretium mauris. Nam ac rutrum odio. Vestibulum feugiat scelerisque elementum. Sed condimentum risus nec sem sodales porta. Proin mollis suscipit neque, facilisis luctus nisi feugiat nec. Duis efficitur orci vel ullamcorper rhoncus. Fusce ante ipsum, facilisis non purus nec, aliquam fringilla nibh. ",
"title": "Title#3"
},
{
"id": "pFFNhyrv3aJJg8Cq18Fx",
"text": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"title": "Title#4"
}
]
import React from 'react';
import { useParams } from 'react-router';
function Page(props) {
const { id } = useParams();
const targetId = id;
const targetUser = props.articles.find(() => targetId === props.articles.id);
console.log("targetUser", targetUser) // undefined
return (
<div>               
{console.log("targetUser", targetUser)}  // undefined
</div>
);
}
export default Page;
import React, { useState, useEffect } from 'react';
import Header from './Header';
import Page from '../pages/Page'
import { db } from "../Firebase";
import {
BrowserRouter as Router,
Route,
Switch
} from 'react-router-dom';
const App = () => {
const [articles, setArticles] = useState([]);
useEffect(() => {
const unsubscribe = db
.collection('articles')
.onSnapshot((snapshot) => {
const newArticles = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}))
setArticles(newArticles)
})
return () => unsubscribe()
}, []);
return (
<div>
<Router> 
<Header />
<Switch>
<Route exact path="/" render={() => <Home articles={articles} />} />
<Route exact path="/page/:id/" render={() => <Page articles={articles} />} />
</Switch>
</Router>     
</div>
);
}
export default App;

对不起。我会改变的。请使用此代码

let targetUser = props.articles.filter(x=>x.id === targetId);
targetUser = targetUser.length > 0 ? targetUser[0] : null;

而不是

const targetUser = props.articles.find(() => targetId === props.articles.id);

props.articles是一个数组。因此,您无法使用props.articles.id访问标题。

props.articles.find将对数组中的每个对象进行迭代。

const targetUser = props.articles.find((article) => targetId.id === article.id);

注意-最初提取id属性->const { id } = useParams();,然后将其分配给targetIdconst targetId = id;。似乎id不是一个对象。如果这是真的,则可以使用targetId而不是targetId.id访问id值。

--编辑--

const targetId = `1oQAPxRl2k7Spev10qFE`;
const props = {
articles: [
{
"id": "1oQAPxRl2k7Spev10qFE",
"text": "Looooorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostr.",
"title": "Title#1"
},
{
"id": "ThRwQIgpLUB7iBq1H8VI",
"text": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.",
"title": "Title#2"
},
{
"id": "aJvajhmoCXbfU7RJVkzn",
"text": "Nuncccc sit amet ante convallis, semper metus ut, ornare leo. Fusce tellus metus, commodo at massa non, auctor pharetra ipsum. Maecenas in suscipit nulla. Nam in consectetur dui, non laoreet purus. Aliquam erat volutpat. Etiam non risus vestibulum, ornare mauris ut, pretium mauris. Nam ac rutrum odio. Vestibulum feugiat scelerisque elementum. Sed condimentum risus nec sem sodales porta. Proin mollis suscipit neque, facilisis luctus nisi feugiat nec. Duis efficitur orci vel ullamcorper rhoncus. Fusce ante ipsum, facilisis non purus nec, aliquam fringilla nibh. ",
"title": "Title#3"
},
{
"id": "pFFNhyrv3aJJg8Cq18Fx",
"text": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"title": "Title#4"
}
]
};
const targetUser = props.articles.find((article) => targetId === article.id);
console.log('Target User: ', targetUser);
console.log('Target User title: ', targetUser.title);

相关内容

  • 没有找到相关文章

最新更新