我正在尝试将来自 API 的产品存储在 React 组件的状态中,然后将它们映射到组件的渲染函数中,但不知何故 this.state.products
是 未定义
。
这是我的组件代码(CategoryProducts.js):
class CategoryProducts extends Component{
constructor(props){
super(props);
this.state = {}
this.products = new Products();
}
async componentWillMount(){
await this.products.getProductsInCategory(this.props.name).then(
(val) => {
this.setState({products: val});
}
)
}
render(){
return(
<Container className='content-container'>
<Row>
<Col md={12}>
<h4 className="mb-0">{this.props.name}</h4>
<hr></hr>
</Col>
</Row>
<Row>
<Col md={2}>
Some space for possible filters in the future
</Col>
<Col md={10}>
{this.state.products.map(function(item, i){
console.log(i);
})}
</Col>
</Row>
</Container>
);
}
}
对 API 的调用是异步的,这是相应的代码:
产品.js:
export class Products extends API {
getProducts() {
return this.get('/products')
}
getCategories(){
return this.get('/products/categories');
}
getProductsInCategory(_category){
return this.get('/products/withcategory/' + _category);
}
}
API 类中的这个方法:
async get(_endpoint) {
let response = await fetch(this.API_url + _endpoint);
return response.json();
}
希望有人能帮我解决这个问题
最佳答案
您正在将 componentWillMount 转变为 promise ,以便该部分不会由 RN 执行:
async componentWillMount(){
await this.products.getProductsInCategory(this.props.name).then(
(val) => {
this.setState({products: val});
}
)
}
试试这个:
constructor(props){
super(props);
this.state = {
products: [] //Or whatever suits you best
}
this.products = new Products();
}
componentWillMount(){
this.products.getProductsInCategory(this.props.name).then(
(val) => {
this.setState({products: val});
}
)
}
关于javascript - React.js 状态 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124534/