Reactjs 使用react-js路由动态路径url
app.js-使用app.js,我得到了左边的菜单列表。使用路由,我 从左侧菜单中选择一个值 这是我第一次像这样使用this.props.location.pathname获取路径Url。当我在菜单中第二次单击时,页面没有刷新,也没有获取路径ex: 因为im使用动态json数据作为左菜单,并使用单个路由文件(消息组件) 我需要通过选择菜单中的一个值来每次刷新页面Reactjs 使用react-js路由动态路径url,reactjs,Reactjs,app.js-使用app.js,我得到了左边的菜单列表。使用路由,我 从左侧菜单中选择一个值 这是我第一次像这样使用this.props.location.pathname获取路径Url。当我在菜单中第二次单击时,页面没有刷新,也没有获取路径ex: 因为im使用动态json数据作为左菜单,并使用单个路由文件(消息组件) 我需要通过选择菜单中的一个值来每次刷新页面 class App extends Component { constructor(){ super()
class App extends Component {
constructor(){
super();
this.state = {
data :[]
}
}
componentDidMount(){
var data =[{"id": 2 ,"name" :"shiva"},{"id": 3 ,"name" :"krishna"},{"id": 5 ,"name" :"ravi"}];
this.setState({data: data});
}
}
render() {
return (
<div className="container">
<div className="col-lg-4">
<div className="container-top">
<div className="col-lg-4 leftmenu-contact-bg">
<div className="ex1">
{this.state.data.map((res,index) => <div className="left-list" key={index}>
<div className="right-content" >
<NavLink to={`/Messages/${res.id}`} activeClassName="nav-link-active" >
<span className="icon-list"><i className="material-icons icon-color">person</i></span><span className="numbers" > {res.name}</span>
</NavLink>
</div>
</div>
)}
</div>
</div>
</div>
</div>
<div className="col-lg-8">
<Switch>
<Route exact path ="/Messages/:id" component={Messages} />
</Switch>
</div>
</div>
);
}
}
Messages.js
import React from "react";
class Messages extends React.Component{
constructor(){
super()
this.state = {
data :[]
}
}
componentDidMount(){
alert(this.props.location.pathname);
}
render(){
return(
<div>
<div className="chat-decription">
</div>
</div>);
}
}
Url path :
http://localhost:3000/Messages/2
http://localhost:3000/Messages/5
类应用程序扩展组件{
构造函数(){
超级();
此.state={
数据:[]
}
}
componentDidMount(){
变量数据=[{“id”:2,“name”:“shiva”},{“id”:3,“name”:“krishna”},{“id”:5,“name”:“ravi”}];
this.setState({data:data});
}
}
render(){
返回(
{this.state.data.map((res,index)=>
人{res.name}
)}
);
}
}
Messages.js
从“React”导入React;
类消息扩展了React.Component{
构造函数(){
超级()
此.state={
数据:[]
}
}
componentDidMount(){
警报(this.props.location.pathname);
}
render(){
返回(
);
}
}
Url路径:
http://localhost:3000/Messages/2
http://localhost:3000/Messages/5
对于这条路线,你们班应该是这样的
import React from 'react';
class Message extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<span>Message id is {this.props.params.id}</span>
)
}
}
export default Message;
从“React”导入React;
类消息扩展了React.Component{
建造师(道具){
超级(道具);
}
渲染(){
返回(
消息id为{this.props.params.id}
)
}
}
导出默认消息;
import React from 'react';
class Message extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<span>Message id is {this.props.params.id}</span>
)
}
}
export default Message;