React js 组件获取状态为 null
2019-12-03
236
尝试将状态作为参数传递给组件时出现错误
我已经提供了 console.log 并且我的状态正在从 api 获取响应
import React, { Component } from 'react';
import api from '../../services/api';
import Products from '../Products';
export default class index extends Component {
constructor(props){
super(props)
this.state={ products: [], filteredProducts:[]}
}
componentWillMount(){
api.get('/products').then( result => this.setState({
products: result.data.listProducts,
filteredProducts: result.data.listProducts
}))
}
render() {
return (
<>
<Products products={this.state.filteredProducts} handleAddToCart={this.handleAddToCart}/>
</>
)
}
}
我的状态以 null 开始,在使用 api 后它正确返回,但传递给我的组件的状态为 null 我的控制台 .log 响应
[]
(5) [{…}, {…}, {…}, {…}, {…}]
错误:
TypeError: Cannot read property 'map' of undefined
const productItems = this.props.productItems.map( product => (
和我的组件产品:
import React, { Component } from 'react'
import util from '../utils';
export default class Products extends Component {
render() {
console.log(this.props);
const productItems = this.props.productItems.map( product => (
<div className="col-md-4">
<div className = "thumbnail text-center">
<a href={`#${product.id}`} onClick={(e)=>this.props.handleAddToCard(e,product)}>
<p>
{productItems.name}
</p>
</a>
</div>
<b>{util.formatCurrency(product.price)}</b>
<button className="btn btn-primary" onClick={(e)=>this.props.handleAddToCard(e,product)}>Add to Cart</button>
</div>
)
)
return (
<div className="row">
{productItems}
</div>
)
}
}
1个回答
您需要将副作用移至
componentDidMount
并等待组件安装,然后执行异步调用并刷新。同时,您需要有一个
if
来防止在状态为空时加载子组件。所以我会将您的代码更改为此。
import React, { Component } from 'react';
import api from '../../services/api';
import Products from '../Products';
export default class index extends Component {
constructor(props){
super(props)
this.state={ products: [], filteredProducts:[]}
}
componentDidMount(){
api.get('/products').then( result => this.setState({
products: result.data.listProducts,
filteredProducts: result.data.listProducts
}))
}
render() {
return (
<>
{this.state.ffilteredProducts.length > 0
? <Products products={this.state.filteredProducts} handleAddToCart={this.handleAddToCart}/>
: null
}
</>
)
}
}
或者您可以使用
spinner
而不是 null
meisam
2019-12-03