我想向 DollarView 组件发送道具,但由于未知原因,它失败了。为了测试这个问题,我使用了一个 Alert 来显示 DollarView 组件的 DollarValue 属性(我在 DollarView 组件中使用了这行代码:)Alert.alert(this.props.dollarValue.toString());
,但是在应用程序刷新时,整个应用程序停止并且我收到此错误:
TypeError: undefined is not an object (evaluating '_this.props.dollarValue.toString')
这是我的代码:
export default class App extends Component {
constructor(props) {
super(props);
this.updateDollar = this.updateDollar.bind(this);
this.state = {
value: 0,
date: 0,
isReady: 'need to update'
};
}
componentWillMount() {
var savedData = (async function init() {
var value = await AsyncStorage.getItem('value');
if (!value) {
value = 0;
} else {
value = parseInt(value);
}
var date = Date.parse(await AsyncStorage.getItem('date'));
return [value, date];
}());
this.setState({
value: savedData[0],
date: savedData[1]
});
}
updateDollar() {
this.setState({
isReady: false
});
axios.get('https://digiarz.com/webservice/api/')
.then(async (response) => {
var dollarRate = response.data.BTC.rates.USD.rate;
var tomanRate = response.data.BTC.rates.TMN.rate;
var dollar = Math.round(tomanRate / dollarRate) * 10;
var newDate = new Date();
await AsyncStorage.setItem('value', dollar.toString());
await AsyncStorage.setItem('date', newDate.toString());
this.setState({
value: dollar,
date: newDate,
isReady: true
});
})
.catch((error) => {
Alert.alert('خطا', 'خطا در دسترسی به اطلاعات. لطفا اتصال اینترنت خود را بررسی نمایید.');
this.setState({
isReady: 'failed'
});
});
}
render() {
var {value, date, isReady} = this.state;
return (
<View style={styles.container}>
<DollarView isReady={isReady} dollarValue={value} date={date} />
<DollarCalculator onUpdate={this.updateDollar} dollarValue={value} />
</View>
);
}
}
和 DollarView 组件:
class DollarView extends Component {
constructor(props) {
super(props);
this.state = {
dollarValue: 0,
value: 0,
date: 0,
isReady: true
};
}
componentWillReceiveProps(nextProps) {
var {dollarValue, value, date, isReady} = nextProps;
this.setState({
dollarValue: dollarValue,
value: value,
date: date,
isReady: isReady
});
}
render() {
var {dollarValue, date, isReady} = this.state;
if (isReady == 'failed') {
var indicator = <Text style={styles.failed}>{dollarValue}</Text>;
} else if (isReady) {
var indicator = <Text style={styles.success}>{dollarValue}</Text>;
} else {
var indicator = <ActivityIndicator size={75} color="#0000ff" />;
}
return (
<View>
{indicator}
</View>
);
}
}
DollarCalculator 组件也会发生同样的事情。