即使传递参数,this.props.match.params也为空

时间:2019-02-14 20:51:41

标签: reactjs

我试图在我的React组件中将params传递给this.props.match,但是即使传递之后,我仍然得到params作为空对象。

render() {
  return (
    <div>
      <div className="boxx">
        {this.state.data.map(ele => (
          <div className="smallbox" key={ele.id}>
            <Link
              to={`${this.props.match.url}/movie1`}
              onClick={() => this.fetchOneMovieData(ele)}
            >
              <img
                src={`http://image.tmdb.org/t/p/w185${ele.poster_path}`}
                alt="movie pic"
              />
            </Link>
          </div>
        ))}

        <Route
          path={`${this.props.match.url}/:topicId`}
          render={props => (
            <OneMovie
              {...props}
              data={this.state.data}
              moviedata={this.state.moviedata}
            />
          )}
        />
      </div>
      {console.log(this.props.match)}
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

您必须使用RouterwithRouter()来访问props.match

例如,您可以像这样使用BrowserRouter中的withRouterreact-router-dom

App.js:

import MyComponent from "./MyComponent";
import {BrowserRouter, Route} from "react-router-dom";

class App extends Component {
    render() {
        return (
            <div className="App">                    
                <BrowserRouter basename='http://localhost:3000'>
                    <Route exact path='/:myparam' component={MyComponent}/>
                </BrowserRouter>
            </div>
        );
    }
}

export default App;

和MyComponent.js:

从“ react-router-dom”导入{withRouter};

class MyComponent extends React.Component {

    render() {
        console.log('props match', this.props.match);
        return <h1>MyComponent</h1>
    }
}

export default withRouter(MyComponent);

从上方在应用上访问http://localhost:3000/asdf会导致控制台输出:

  

道具匹配对象{路径:“ /:myparam”,网址:“ / asdf”,isExact:true,参数:{…}}

然后您可以访问this.props.match.params.myparam上的:myparam的值,在本示例中为您提供:

  

asdf