反应如何更新组件

时间:2019-06-12 09:39:33

标签: reactjs

以下是组件:

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时尚未添加到状态,因此如何在状态更改后更新组件?

1 个答案:

答案 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>
    );
 } 
 }