Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

javascript - TypeError: Cannot read property 'params' of undefined at App React Router

Whenever I console log props.match.params, I get an error:

TypeError: Cannot read property 'params' of undefined at App. I'm not sure this is relevant, but even if I console.log(props) I get four empty arrays. Here is all the relevant code:

Home.js

import React from "react";
import App from "./App";
import { render } from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
} from "react-router-dom";

const Home = () => {
  return (
    <div>
      <Router>
        <Route exact path="/">
          <App />
        </Route>
        <Route path="/:roomCode" component={App} />
      </Router>
    </div>
  );
};

export default Home;

App.js (only the relevant part)

const App = (props) => {

  console.log(props.match.params);

};

export default App;
const appDiv = document.getElementById("app");
render(<App />, appDiv);

I have been trying to figure this out for the past two days. Nothing works. Also, history.push also doesn't work, returns a very similar error. I have a feeling react-router-dom is broken in my project. Help is much appreciated.

Edit: Here is the codesandbox: https://codesandbox.io/s/reverent-microservice-iosu2?file=/src/App.js

question from:https://stackoverflow.com/questions/65914431/typeerror-cannot-read-property-params-of-undefined-at-app-react-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your Home Component is the root of all your components so it needs to be pass to render function not your App which is a descendent of Home.

after that change you need to change this line in your Home Component:

<Route exact path="/" render={(props) => <App {...props} />} />
import React from "react";
import App from "./App";
import { render } from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
} from "react-router-dom";

const Home = () => {
  return (
    <div>
      <Router>
        <Route exact path="/" render={(props) => <App {...props} />} />
        <Route path="/:roomCode" component={App} />
      </Router>
    </div>
  );
};

export default Home;

here is how to render it:


const appDiv = document.getElementById("app");
render(<Home />, appDiv);

now you can get the props


const App = (props) => {
  console.log(props.match.params);
};

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...