【发布时间】:2021-03-03 11:45:47
【问题描述】:
在我的一个 React 项目中,我创建了主页以及照片和视频组件。我得到的所有数据都来自 API。现在在主页中,我从 JSON 获取数据如下(示例)
export const data = {
list : [
{
id:'abc123',
type:'content',
name:'videos'
},
{
id:'pqr124',
type:'content',
name:'photos'
}
],
}
主页分别有照片和视频的“查看全部”链接。现在,当单击“查看所有照片”时,“照片”路由到“照片”组件,URL 为 /content/list/pqr124,“视频”组件为 /content/list/abc123。
所以在 Home 组件中
const [name, setName] = useState('')
const [newPhotoId, setNewPhotoId] = useState('')
const [newVideoId, setNewVideoId] = useState('')
useEffect(() => {
loadData()
})
const loadData = () => {
try {
fetch('data').then(data2 => data2.json()).then(data3 => {
if(data3.list.name == 'photos') {
setNewPhotoId(data3.list.id)
} if(data3.list.name == 'videos') {
setNewVideoId(data3.list.id)
}
})
}
}
现在创建了两个链接
See All (for photos) <Link to={{ pathname: `/content/list/${newPhotoId}` />
See All (for videos) <Link to={{ pathname: `/content/list/${newVideoId}` />
同时在 App.js 中的组件路由是 as
<Router>
<Switch>
<Route to="/content/list/:someId" component={PhotosVideos} } />
</Switch>
</Router>
现在为了无缝路由,我创建了一个中间组件“PhotosVideos”,它获取相应的参数并相应地路由到该组件。
照片视频
const {someId} = useParams()
const [section, setSection] = useState('')
useEffect(() => {
getData()
})
const getData = () => {
try {
fetch(`${someId}/artId=${xyz123}`).then(data => data.json()).then(newData =>
setSection(newData.data.meta_data)
)
}
}
在 getData 我收到如下数据(只是一个例子) 当 someId 为 'abc123' 时
data = [
meta_data: "videos",
list: {...}
]
当 someId 为 'pqr124' 时
data = [
meta_data: "photos",
list: {...}
]
然后我将条件设置为 ``` if(section == 'Photos') { ...照片部分 } 如果(部分=='视频'){ ...视频部分 }
When navigating from photos to videos and vice-versa, What could be appropriate solution? I mean What conditions should be applied in App.js in Routing or Do I need to create each seperate components?
【问题讨论】:
标签: javascript reactjs