我正在使用地图使用axios查看所有帖子。我只想在单击特定帖子以显示更多信息时显示。我正在使用react参数。但这不起作用。
这是我的一个组成部分
import React, {Component} from 'react';
import Album from './album'
import {Link, BrowserRouter as Router, Route} from 'react-router-dom'
import axios from "axios"
class ViewDataAPI extends Component{
state = {
posts: []
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/comments')
.then(response => {
this.setState({
posts: response.data
})
})
.catch(error => console.log('error'))
}
render(){
let { posts } = this.state
if(posts.length === 0){
return <h1>Loading...</h1>
}
else{
return(
<Router>
<div className="header">
<div className="container">
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="text-center mb-20">
<h1>View Data From API</h1>
<p>using jsx-component, props, state, map in react </p>
</div>
</div>
</div>
<div className="row">
{
posts.map(post =>
{
return (
<Album
key={post.id}
name={post.name}
email = {post.email}
body = {post.body}
view = {post.id}
/>
)
}
)
}
</div>
{/* here is im using params, and to match by clicking specific id to show/view more information */}
<div className="row">
{posts && (
<Route path="/album/:albumId"
render = {({match}) => (
<ViewPosts {...posts.find(pv => pv.id === match.params.albumId)} />
)}
/>
)}
</div>
</div>
</div>
</Router>
)
}
}
}
export default ViewDataAPI;
// This component using for show details
const ViewPosts = ({posts}) =>{
return(
<div className="col-lg-6">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<div className="album">
<h3>{posts.name}</h3>
<h3>{posts.email}</h3>
<Link to="./">Back To Home</Link>
</div>
</div>
</div>
</div>
);
}
这是具有链接的相册组件
import React, {Component} from 'react'
import {Link} from "react-router-dom"
class Album extends Component{
render(){
return(
<div className="col-lg-6">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<div className="album">
<h3>{this.props.name}</h3>
<p>{this.props.email}</p>
<p>{this.props.body}</p>
<Link to={`/album/${this.props.view}`}>View</Link>
</div>
</div>
</div>
</div>
);
}
}
export default Album;
https://react-pin.netlify.com/
请点击上面的链接,转到我要执行的操作。请首先转到一个"View Data From API"
我的github链接https://github.com/sultan0/reactpin
答案 0 :(得分:0)
路由参数是一个字符串。没有隐式类型转换
与===
运算符。因此,您必须明确地执行此操作。请看到
Comparison operators进行进一步说明。
扩展...
运算符在这里放错了位置。
解决方案是:
<ViewPosts posts={posts.find(pv => pv.id === parseInt(match.params.albumId))} />
更新
您想使用React路由器中的Switch组件:
Switch的独特之处在于它专门呈现一条路由。相比之下,与位置匹配的每个Route都将进行包含性渲染。
请参阅react router documentation。
我创建了一个pull request作为示例。希望对您有所帮助。