【问题标题】:React - in which component should I do http requests?React - 我应该在哪个组件中执行 http 请求?
【发布时间】:2018-01-03 07:42:54
【问题描述】:

在我的“Home.js”组件中,我想显示使用 http 请求(使用 axios)获取的产品列表。我还有一个“Product.js”组件,我还需要以同样的方式获取产品。我不清楚在哪里放置这种代码的指导方针。

如果我将这些请求放在它们各自的组件(Home 和 Product)中,那么我猜它们必须是类组件?它们不能是无状态组件,因为产品数据需要存储在组件自己的状态中。我猜,父 App.js 无法访问该数据? (不过我不知道这是否重要)。

但是如果我将所有这些东西都放在父组件中,然后将其传递给组件,那就有点麻烦了。我不想在所有页面上发出所有这些请求,所以我需要有条件地检查哪个是当前 url。而且我不能利用反应路由器的match.params 来获取“:product”参数。我开始编写一些代码,在App.js 中提出请求,但它似乎不太顺利。我需要获取名为:product的参数,我想我可以通过使用更多的正则表达式来解决它:

class App extends Component {

  state = {

    loading: false,
    product: [],
    products: []

  }

    componentWillMount() {

    const re = new RegExp('^/product');            

    if (window.location.pathname === '/' ){              // if url is '/', get products

            this.setState({loading: true})

            axios.get('/api/getproducts')
               .then(response => {

                this.setState({   
                    products: response.data,
                    loading: false
                })
            }))   
}
           // check if url begins with 'product', get product
else if  (re.test(window.location.pathname)){       

            // axios.get('/api/getproduct/' + match.params.product)   //need :product param
            // .then(response => {

        // })

    }

So, should I instead do data fetching in the components/routes where they need to be loaded, storing it in their own state?

我认为建议将所有数据放在顶部组件中。但在这种情况下,推荐的方式是什么?

【问题讨论】:

    标签: reactjs xmlhttprequest react-router-v4


    【解决方案1】:

    虽然这取决于你,但我想说的是,在更高阶的组件上发出请求确实更好,只要它们是相关的。

    所以在这种情况下,我会说你最好的选择是在你的 Home 组件而不是 App 中执行 getproducts 请求。这样做的原因是因为应用程序往往是整个应用程序中所有组件的起点(正如它的名字所暗示的那样)。对于小型应用程序,这可能没有什么不同,但是假设您正在制作一个更大的应用程序,其中包含数十个组件,每个组件都有自己的必要请求。如果所有这些都在 App 组件中,那将是完全混乱的。

    更不用说,如果您在应该在某个 URL 中呈现的组件中,您不必担心检查它。如果安装了相关组件,则会发出请求。

    现在对于第二部分,在 Product 组件中发出 getproduct 请求似乎更有意义。由于它可能会获取与产品相关的数据,对吗?

    所以无论如何,鉴于帖子中提到的信息,我建议如下:

    对于Home.js 文件:

    export default class Home extends React.Component {
      constructor (props) {
        super(props)
    
        this.state = {
          loading: true,
          products: []
        }
      }
    
      componentWillMount () {
        axios.get('/api/getproducts')
        .then(response => {
    
          this.setState({   
              products: response.data,
              loading: false
          })
        })
      }
    
      render () {
        const { loading, products } = this.state
        if (loading) {
          return (
            <div>Loading...</div>
          )
        }
    
        // Note: I am using product.id and product.name, but it really is whatever you are using to identify your different products
        // I have also made it in a way that will link to the product
        return (
          <ul>
            products.map(product =>
              <li>
                <Link to=`/${product.id}`>
                   product.name
                </Link>
              </li>
            )
          </ul>
        )
      }
    }
    

    对于Product.js 文件:

    export default class Product extends React.Component {
      constructor (props) {
        super(props)
    
        this.state = {
          loading: true,
          product: []
        }
      }
    
      componentWillMount () {
        axios.get(`/api/getproduct/${this.props.match.params.product}`)
        .then(response => {
    
          this.setState({   
              product: response.data,
              loading: false
          })
        })
      }
    
      render () {
        const { loading, product } = this.state
        if (loading) {
          return (
            <div>Loading...</div>
          )
        }
    
        return (
         <div>
         {product.whatever}
         </div>
        )
      }
    }
    

    【讨论】:

    • 感谢您的建议,我想这可能是最好的方法,也是最简单的方法。也许组件请求自己的数据是最自然的。
    • 在这种特殊情况下我会这么说。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2021-02-16
    • 2019-07-05
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多