首页 > 解决方案 > 无法读取 React 中未定义的属性“参数”

问题描述

我是反应新手。我正在尝试使用react-router-dom. 但无法获得参数

TypeError:无法读取未定义的属性“参数”。

我尝试了已经存在但没有任何帮助的解决方案。我犯了什么错误?有人可以向我解释吗?提前致谢。

Main零件:

function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/edit/:id" component={Edit} exact={true}>
            <Edit />
          </Route>
        </Switch>
      </Router>
    </div>
  );
}
export default App;

Edit零件:

class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: this.props.match.params.id
    };
  }

  render() {
    return <h2>Edit Page</h2>;
  }
}
export default Edit;

标签: javascriptreactjsreact-router-dom

解决方案


注意:我提供了我的答案,useParams因为您的原始问题涉及它。除此之外,如果您必须使用类组件,通常this.props.match.params.id应该可以工作,因为您是通过Route.

你应该useParams在你的Edit组件中使用它,它应该是一个功能组件。

function Edit() {
  const { id } = useParams();
  return (
    <div>{id}</div>
  )
}

Also, I don't know which React Router version you use, but if you are not using v6, you probably want to use the Route part like this:

<Router>
  <Switch>
    <Route path="/edit/:id" component={Edit} exact />
  </Switch>
</Router>

推荐阅读