我在Route中设置了参数。它们从我的组件出现在控制台中,但出现“未定义”错误。
<Router>
<App>
<Switch>
<Route exact path='/data/:param' component={data} />
</Switch>
</App>
</Router>
组件
class Data extends Component {
constructor(props) {
super(props);
async componentDidMount() {
console.log(this.props.match.params.param)
...
export default Data;
如果我可以在控制台中看到它们,为什么仍然出现错误?
未处理的拒绝(TypeError):无法读取未定义的属性'params'
答案 0 :(得分:2)
您需要确保导入的Route
是正确的Data
。
import Data from './Data';
...
<Route exact path='/data/:param' component={Data} />
...
由于您的组件withRouter
已经是Data
的子代,因此不需要使用Route
高阶组件来包装该组件。
FWIW做
componentDidMount() {
console.log(this.props.match && this.props.match.params.param);
}
此外,您在执行async
时可能不需要componentDidMount()
。这也可能是您需要添加上述防御代码的原因。
PS:console.log()
可以显示评估的数据,通常在对象eval旁边用i
表示。