以下是组件:
class ProductList extends Component {
componentWillMount() {
getProducts((err, products) => {
if(err) return console.log('error: ', err);
this.setState({products})
})
}
render() {
const data = this.state.products;
return (
<div>
<Table dataSource={data}>
<Column title={'Id'} dataIndex={"_id"} key={'_id'}/>
<Column title={'Name'} dataIndex={"name"} key={'name'}/>
<Column title={'Price'} dataIndex={"price"} key={'price'}/>
<Column title={'Type'} dataIndex={"type"} key={'type'}/>
<Column title={'Category'} dataIndex={"category"} key={'category'}/>
</Table>
</div>
);
}
}
我收到Cannot read property 'products' of null
错误,我认为这是因为Table
渲染products
时尚未添加到状态,因此如何在状态更改后更新组件?
答案 0 :(得分:0)
class ProductList extends Component {
constructor(props) {
super(props);
this.state = {products: []};
}
componentWillMount() {
getProducts((err, products) => {
if(err) return console.log('error: ', err);
this.setState({products})
})
}
render() {
const data = this.state.products;
return (
<div>
<Table dataSource={data}>
<Column title={'Id'} dataIndex={"_id"} key={'_id'}/>
<Column title={'Name'} dataIndex={"name"} key={'name'}/>
<Column title={'Price'} dataIndex={"price"} key={'price'}/>
<Column title={'Type'} dataIndex={"type"} key={'type'}/>
<Column title={'Category'} dataIndex={"category"} key={'category'}/>
</Table>
</div>
);
}
}