【发布时间】:2018-12-28 07:22:55
【问题描述】:
我有一组异步加载的 Reacts 组件来处理大型数据集。我有一个通过react-spinnersBeatLoader 工作的初始加载程序,它工作正常。当我尝试在其父组件中传递 productsLoading 状态时,当我尝试使用 Loading inventory... 消息复制此效果时,我的问题出现了,就像我在 index.jsx 级别对仓库加载状态所做的那样。
我只是试图让回调在子组件中工作。
index.jsx:
import React from 'react'
import { withRouter } from 'react-router-dom'
import WarehouseDetails from './warehouse-details'
import { BeatLoader } from 'react-spinners';
;
class WarehouseReport extends React.Component {
state = {
warehouse: {
name: '',
sales: '',
cost: ''
},
categories: [],
products: [],
warehouseLoading: true, <<< top level loader
categoriesLoading: true,
productsLoading: true, <<< component level
}
componentDidMount() {
this.loadWarehouseInfo()
}
loadWarehouseInfo = () => {
return fetch(`//${window.location.host}/${this.props.match.params.account_id}/warehouse_info/${this.props.match.params.warehouse_id}`)
.then(response => response.json())
.then(json => {
this.setState({
warehouse: {
name: json.warehouse_name,
sales: json.warehouse_sale_total,
cost: json.warehouse_cost_total
},
warehouseLoading: false
}, this.loadCategoryInfo)
})
}
loadCategoryInfo = () => {
return fetch(`//${window.location.host}/${this.props.match.params.account_id}/warehouse_info/${this.props.match.params.warehouse_id}/categories`)
.then(response => response.json())
.then(json => {
this.setState({
categories: json,
categoriesLoading: false
}, this.loadProductInfo)
})
}
loadProductInfo = () => {
return fetch(`//${window.location.host}/${this.props.match.params.account_id}/warehouse_info/${this.props.match.params.warehouse_id}/category_products/${this.state.categories.map(category => category.id).join(',')}`)
.then(response => response.json())
.then(json => {
this.setState({
products: json,
productsLoading: false, <<<< setup states
loading: false
})
})
}
render() {
const { warehouse, categories, products, warehouseLoading } = this.state
return <div>
{ warehouseLoading ? <BeatLoader
color={'#4db3bf'}
/> : <WarehouseDetails warehouse={warehouse} categories={categories} products={products} /> }
</div>
}
}
export default withRouter(WarehouseReport)
当我深入到我试图为其设置加载器的组件时,我有这个:
category-details.jsx:
import React from 'react'
import ProductDetails from './product-details'
import NumberFormat from 'react-number-format';
export default function CategoryDetails({ name, count, products, productsLoading }) {
<<< state is passed down; passing state outside the curly brackets only replaces the following component with the loading statement/item)
return <div>
<div><h3>{name}</h3></div>
<div>{count} products found</div>
<h4>Products</h4>
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Rental $</th>
<th>Sale $</th>
</tr>
</thead>
<tbody>
{ this.state.productsLoading ? 'Loading inventory...' : products.map(product => <ProductDetails
{...product}
/>) <<<< component-level loader here
}
</tbody>
</table>
</div>
}
安装此加载程序的正确方法是什么?感谢您抽出宝贵时间,我仍在处理 React 中的状态。
【问题讨论】:
标签: reactjs asynchronous ecmascript-6 fetch state