reactjs - React Js 从 URL 获取参数

标签 reactjs react-router

我正在尝试使用 React js 获取 url 参数。 我的路线是

<Route exact path="/store/product-details/:id" component = {StoreProductDetails} />

产品详细信息.js

componentDidMount(){
      let id = this.props.match.params.id
      fetch(MyGlobleSetting.url + 'product/'+ id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
    }

enter image description here

最佳答案

您可以使用 useParams 钩子(Hook)或使用 React-router 中的 withRouter HOC 包装基于类的组件。你可以在他们的documentation中看到一个例子。 .

使用功能组件

import React, {useEffect} from 'react';
import {useParams} from 'react-router-dom';

function Child() {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { id } = useParams();

  useEffect(() => {
     fetch(MyGlobleSetting.url + 'product/'+ id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
  }, [])
}

使用类组件

import React, {Component} from 'react';
import { withRouter } from 'react-router-dom';

class myComponent extends Component {

  componentDidMount(){
     const {match} = this.props

     fetch(MyGlobleSetting.url + 'product/'+ match.params.id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
  }
}

export default withRouter(Child);

关于reactjs - React Js 从 URL 获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65629257/

相关文章:

dom - 在 React 中更改文档标题?

javascript - 从 React.JS 状态调用方法

reactjs - React Flux 架构有什么好的 Http 库吗

javascript - ReactJS:如果在 promise 解决后经过身份验证,则呈现私有(private)路由

reactjs - 如何在 Reactjs 中单击按钮时重定向到另一个页面

javascript - 当父级中的 setState() 时,子级中的 componentWillReceiveProps 不会收到新 Prop

javascript - 从渲染列表中获取点击元素的 ID

javascript - React-admin 自定义 noResult 设计

reactjs - 如何使用 react-router 执行多个可选参数?

reactjs - 使用 React 路由器定义传递额外参数