首页 > 解决方案 > this.props.match.params 即使在传递参数时也是空的

问题描述

我试图在我的 React 组件中传递paramsthis.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>
  );
}

标签: reactjs

解决方案


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

例如,您可以像这样使用BrowserRouterand withRouterfrom react-router-dom

应用程序.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,参数:{...}}

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

自卫队


推荐阅读