我想将道具发送到DollarView组件,但由于未知原因,它失败了。为了测试此问题,我使用警报显示了DollarView组件的DollarValue Prop(我在DollarView组件中使用了此代码线:Alert.alert(this.props.dollarValue.toString());
),但是在App Refresh上,整个应用程序停止,我会收到此错误:
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>
);
}
}
同一件事也发生在美元的组件中。
代码中的async
await
对不起作用。
saveData
是一个承诺,所以 saveData[0]
是未定义的,这就是为什么您遇到错误的原因。
您可以做到这一点:
async componentWillMount() {
var value = await AsyncStorage.getItem('value');
if (!value) {
value = 0;
} else {
value = parseInt(value);
}
var date = Date.parse(await AsyncStorage.getItem('date'));
this.setState({
value,
date,
});
}