【问题标题】:Extract values from url using React使用 React 从 url 中提取值
【发布时间】:2021-08-29 22:27:32
【问题描述】:

我正在使用 React,我需要将用户导航到个人资料页面,即 mydomain.com/profile/myusername,但我不确定如何从 url 中提取“myusername”?我的代码片段如下,请帮助!

非常感谢

路由

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div>
                    <Route path="/" component={Main} exact />
                    <Route path="/profile" component={Profile} exact />
                </div>
            </BrowserRouter>
        );
    }
}

export default App;

我的超链接

<Link to={`profile/${obj.username}`}>{obj.username}</Link>

我的个人资料页面

import React, { Component } from 'react';

class Profile extends Component {

  componentDidMount() {
  }

  render() {

    return (
      <div>
        <h1>myusername</h1>
      </div>
    );
  }
}

export default Profile;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你必须像这样声明你的路线:

    <Route path="/profile/:username" component={Profile} exact />
    

    然后在您的组件中,您可以通过以下方式访问用户名:

    this.props.match.params.username
    

    像这样:

    render() {
      return (
        <div>
          <h1>{ this.props.match.params.username }</h1>
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      您可以如下定义路由:

      <Route path="/profile/:id" component={Profile} exact />
      

      在组件中:

      const id = this.props.match.params.idj
      

      【讨论】:

        【解决方案3】:

        您可以如下定义路线,

        <Route path="/profile/:username" component={Profile} exact />
        

        然后在你的组件中访问用户名,

        this.props.match.params.username 
        

        【讨论】:

          【解决方案4】:

          有两种方法可以做到: 首先通过useParams() in react-router-dom 或通过道具:

          <Route path="/profile/:username" component={Profile} exact />
          

          通过以下方式获取:

          const username = props.match.params.username || null
          

          但我更喜欢在 react-router-dom 中使用默认的 useParams():

          let useParam =  {} as any;
              useParam = useParams();
              let Param = useParam.any || false;
          

          美好的一天!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-09-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-13
            • 1970-01-01
            相关资源
            最近更新 更多