An *_*ơng 4 reactjs react-router-dom
我有一条路线<Route path="post/:id" element={<PostByIdPage />} />
我怎样才能id像propsreact router dom v6一样获取参数?
这是我的 PostByIdPage 组件:
import React, { Component } from 'react';
import OneSecret from '../OneSecret';
import getSecretsPublic from '../../../action/getSecretsPublic';
import { connect } from 'react-redux';
export class index extends Component {
constructor(props) {
super(props);
this.state = {
secretPublic: {
content: ''
}
}
let id = decodeURI(window.location.pathname.substring(6));
let params = {
id: id
}
this.props.getSecretsPublic(params)
.then(res =>{
if (res.type === 'ERROR_MESSAGE') {
return;
}
this.setState({secretPublic: res.payload.data[0]})
});
}
render() {
return (
<div>
<OneSecret element={this.state.secretPublic} key={this.state.secretPublic.id} />
</div>
)
}
}
export default connect(null, {getSecretsPublic})(index)
Run Code Online (Sandbox Code Playgroud)
我正在使用 window.location.pathname 和 split 来获取参数,但我想从 props 获取参数以重新渲染()基于参数的组件
小智 5
回答有点晚,但你可以轻松实现。一旦您使用react-router-dom中的{useParams},<this.props.match>将可用,但对于基于类的组件来说有点棘手。如果使用功能组件,您可以选择直接使用 {useParams} 并且 props.match 将可用。对于像您的案例这样的基于类的组件,您可以使用高阶组件来执行此操作:
import { useParams } from 'react-router-dom';
export function withRouter(Children) {
return (props) => {
const match = { params: useParams() };
return <Children {...props} match={match} />
}
}
class PostByIdPage extends Component {
render() {
return (
<div className="App">
<h1>Page for {this.props.match.params.id}</h1>
</div>
);
}
}
export default withRouter(PostByIdPage);
Run Code Online (Sandbox Code Playgroud)
现在在基于类的组件中,您可以通过以下方式访问 id:
this.props.match.params.id
Run Code Online (Sandbox Code Playgroud)
不再出现“this.props.match 未定义”的错误
| 归档时间: |
|
| 查看次数: |
5947 次 |
| 最近记录: |