【发布时间】: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