为什么this.state.records.amount未定义?

时间:2016-12-22 08:37:29

标签: reactjs

我正在学习React,并在我的州遇到一些麻烦。我正在尝试获取一个函数,以便在呈现组件时将class Records extends React.Component { constructor(props) { super(props); this.state = { records: [] } this.handleNewRecord = this.handleNewRecord.bind(this); this.handleDeleteRecord = this.handleDeleteRecord.bind(this); this.surplus = this.surplus.bind(this); this.debt = this.debt.bind(this); this.total = this.total.bind(this); } componentDidMount() { this.setState({ records: this.props.records }) } handleNewRecord(record) { let records = this.state.records.slice(); records.push(record) this.setState({ records: records }) } handleDeleteRecord(record) { let records = this.state.records.slice(); let index = records.indexOf(record) records.splice(index, 1) this.setState({ records: records }) } surplus() { console.log(this.state.records[0].amount) } debt() { console.log("debt") } total() { console.log("total") } render() { const records = this.state.records.map((record) => <Record record={record} key={record.id} handleDeleteRecord={this.handleDeleteRecord}/> ) return ( <div className="container"> <h1>Records</h1> <div className="row"> <AmountBox panelClass="panel panel-primary" panelHeader="Surplus" calculatedAmount={this.surplus()} /> <AmountBox panelClass="panel panel-warning" panelHeader="Debt" calculatedAmount={this.debt()} /> <AmountBox panelClass="panel panel-success" panelHeader="Total" calculatedAmount={this.total()} /> </div> <RecordForm handleNewRecord={this.handleNewRecord}/> <table className="table"> <thead> <tr> <th>Date</th> <th>Title</th> <th>Amount</th> <th>Actions</th> </tr> </thead> <tbody> {records} </tbody> </table> </div> ) } } 记录到我的控制台,但它显示为未定义。如果有人能够解决这个问题,那将非常感激。

记录组件:

class AmountBox extends React.Component {
constructor(props) {
    super(props);   
}

render () {
  return (
            <div className="col-md-4">
                <div className={this.props.panelClass}>
                    <div className="panel-heading">
                        <h3 className="panel-title">{this.props.panelHeader}</h3>
                    </div>
                    <div className="panel-body">
                        <p>
                            {this.props.calculatedAmount}
                        </p>
                    </div>
                </div>
            </div>          
    )
}
}

Amount Box组件:

\r\n

1 个答案:

答案 0 :(得分:2)

this.state.records[0].amountundefined,因为在首次渲染时,您将records设置为[](在构造函数中)。

setState会触发第二次渲染,但在第一次渲染中,state的{​​{1}}更改将不适用。

因此,您需要一些防御性代码,以确保setState有项目。

this.state.records