2016-12-22 4 views
1

Я в процессе обучения Реагирую и испытываю определенные проблемы с моим состоянием. Я пытаюсь получить функцию для регистрации this.state.records.amount на моей консоли, когда компонент отображается, но он отображается как неопределенный. Если кто-то может понять это, это будет ОЧЕНЬ высоко ценится.Почему this.state.records.amount не определен?

отчеты Компонент:

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> 
    ) 
}  
} 

Количество компонентов Box:

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>   
    ) 
} 
} 

ответ

2

this.state.records[0].amount является undefined, потому что на первом визуализации вы устанавливаете records в [] (в конструкторе).

setState будет вызывать второй рендер, но в первом рендере изменения state на setState не применяются.

Итак, вам нужен защитный код, который гарантирует, что у this.state.records есть предметы.

surplus() { 
    this.state.records.length ? this.state.records[0].amount : 0; 
} 
+0

или использовать что-то вроде lodash '_.get' метода, так что вы всегда не должны проверить целый тракту каждый раз :) –

+0

Спасибо Дэвин. что это было ... – Jmorel88

+0

Что делать, если я хотел записать все суммы? как только я удаляю '[0]' Я снова получаю undefined – Jmorel88

Смежные вопросы