reactjs - React - 我应该在哪个组件中执行 http 请求?

标签 reactjs xmlhttprequest react-router-v4

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

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

但是如果我把所有这些东西都放在父组件中,然后将其传递给组件,那就有点麻烦了。我不想在所有页面上发出所有这些请求,因此我需要进行条件检查以查看哪个是当前网址。而且我无法利用 React 路由器的 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?

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

最佳答案

尽管这取决于您,但我想说,只要相关,就向高阶组件提出请求确实更好。

因此,在这种情况下,我认为最好的选择是在 Home 组件而不是应用程序中执行 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>
    )
  }
}

关于reactjs - React - 我应该在哪个组件中执行 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48069136/

相关文章:

javascript - 如何使用 react.js 在 Apache 服务器上生成动态 &lt;meta&gt; 标签

javascript - 将参数从 React-router 传递到 Apollo Client 2.1 中的查询组件

javascript - React-Native - KeyboardAvoidingView - 错误

javascript - Redux reducers 初始化相同的状态键

css - 单击标签不会单击 React 中的复选框?

javascript - 设置Access-Control-Allow-Origin可能存在的安全问题

javascript - 在 Gatsby 中获取 url 参数

javascript - 如何在任何 XMLHttpRequest 完成时运行函数?

javascript - 为什么发送到 Node/Express 服务器的 XMLHttpRequest 中的对象是空的?

reactjs - React 路由器 URL 参数不起作用