【问题标题】:React-router get optional query parameterReact-router 获取可选的查询参数
【发布时间】:2021-10-25 05:21:42
【问题描述】:

我一直在研究一些关于堆栈溢出的示例,用于在 react-router 中定义可选的查询参数,最后发现它可以像这样完成

 {
    path: '/forms/simulacao/:journeyId?',
    exact: true,
    name: 'Home',
    component: Home,
    authRequired: true
  }

所以在下一步我想检索“journyeId”的查询参数,如果它在那里,所以我尝试了

const history=useHistory()
console.log(history.location)  

但这似乎不起作用,应该有什么解决方法??

“反应路由器”:“^5.1.2”, "react-router-dom": "^5.1.2",

【问题讨论】:

    标签: reactjs react-router react-router-dom react-router-v5


    【解决方案1】:

    有一个钩子:react-router-dom 中的 useParams

    <Route path="/item/:id" component={NewsPage} />
    

    之后,在 NewsPage 组件中,我将能够像这样从路由中获取 ID:

    const params = useParams()
    fetchNews(params.id).then(data => setNews(data))
    

    等等

    【讨论】:

      【解决方案2】:

      首先,:journeyId 是您的路由的一部分,而不是查询参数。查询参数应定义为路径:'/forms/simulacao?journeyId=something',

      类似的,

      https://reactrouter.com/web/example/query-parameters

      【讨论】:

        【解决方案3】:

        首先你必须用路由器导出组件

        export default withRouter(MyComp);
        

        那么你就会在 props 中有匹配的参数

        let {journeyId} = props.match.param;
        

        您的完整组件将是

        const MyComp = (props)=>{
            let {journeyId} = props.match.param;
        
            return ...
        }
        export default withRouter(MyComp);
        

        【讨论】:

          猜你喜欢
          • 2017-08-30
          • 2015-07-03
          • 2017-01-31
          • 2018-09-18
          • 2019-11-09
          • 1970-01-01
          • 2014-05-27
          • 2021-06-14
          • 2016-06-20
          相关资源
          最近更新 更多