我學習流的類型,但我得到了很多,我不明白的問題。 其中之一是如下: 我初始化bill
狀態我們null
然後我從API獲取它,並用所獲取的票據更新狀態。我知道,如果this.state.bill
是null
我不能訪問它的任何財產,所以我只有this.state.bill
訪問屬性的if
語句中這樣的:意外流動型誤差可能爲null的對象
class BillPaymentPage extends Component<*, props, *> {
state = {
bill: null,
};
componentDidMount() {
this.fetchBill(this.props.id);
}
fetchBill = async (id: string) => {
const bill = await getBillById(id, this.props.token).catch(e =>
console.log(e),
);
this.setState({ bill });
};
....
render() {
if (this.state.bill) {
const totalPayment = this.state.bill.payment
.reduce((acc, curr) => acc + curr.amount, 0)
.toFixed(3);
return (
<Card>
<PaymentForm
bill={this.state.bill}
submitPayment={this.submitPayment}
billStatus={this.state.bill.status}
/>
<h3>
<FormattedMessage id="label.total" /> :{' '}
<FormattedNumber
value={this.state.bill.total}
type="currency"
currency="tnd"
/>
</h3>
<h3>
<FormattedMessage id="label.totalPayment" /> :{' '}
<FormattedNumber
value={totalPayment}
type="currency"
currency="tnd"
/>
</h3>
<PaymentList
deletePayment={this.deletePayment}
payment={this.state.bill.payment}
/>
</Card>
);
}
return <Loader />;
}
}
雖然我用if(this.state.bill)
流仍然告訴我這個錯誤:
app/components/pages/bills/BillPaymentPage.js:99
99: billStatus={this.state.bill.status}
^^^^^^ property `status`. Property cannot be accessed on possibly null value
99: billStatus={this.state.bill.status}
^^^^^^^^^^^^^^^ null
app/components/pages/bills/BillPaymentPage.js:104
104: value={this.state.bill.total}
^^^^^ property `total`. Property cannot be accessed on possibly null value
104: value={this.state.bill.total}
^^^^^^^^^^^^^^^ null
app/components/pages/bills/BillPaymentPage.js:119
119: payment={this.state.bill.payment}
^^^^^^^ property `payment`. Property cannot be accessed on possibly null value
119: payment={this.state.bill.payment}
^^^^^^^^^^^^^problem
謝謝,但這並沒有解決同樣的錯誤仍然存在的問題。 –
@ziedhajsalah,你這次得到什麼錯誤?有一個截圖? – Chris
同樣的錯誤我會添加一個截圖。 –