这个错误通常在React中的路由器中使用。如果您正在使用React路由器并且遇到此错误,则可能是一个名称错误或您忘记传递props
。请确保this.props.location.pathname
位于路由器内部,并检查确保正确地传递了 props
。以下是一个示例代码片段,可能会发生此错误:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
class App extends React.Component {
render() {
return (
);
}
}
const Home = () => {
return (
Home
Current pathname: {this.props.location.pathname}
);
}
const About = () => {
return (
About
Current pathname: {this.props.location.pathname}
);
}
const Contact = () => {
return (
Contact
Current pathname: {this.props.location.pathname}
);
}
const Sitemap = () => {
return (
Sitemap
Current pathname: {this.props.location.pathname}
);
}
在此示例中,我们尝试从未定义的props
访问location.pathname
。要解决此问题,我们应该从props
对象中访问 location.pathname
,并需要将props
传递给组件。将Home
组件更新如下:
const Home = (props) => {
return (
Home
Current pathname: {props.location.pathname}
);
}
或者使用解构:
const Home = ({ location }) => {
return (
Home
Current pathname: {location.pathname}
);
}