我在映射有关货币的数组时遇到问题。因此,如您所见,有一个带字符串的curriences数组。我正在使用Picker在它们之间进行选择,而我具有Picker中onValueChange
道具所包含的功能,然后出现了从Picker中选择项目的问题。
首先,我可以从选择器中选择任何项目,但是当我要再次选择时,我在列表中之前只是这个选择的项目:
然后我选择了EUR。当我想再次选择一个项目时,我只有这个:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9janFxMS5wbmcifQ==” alt =“有第二步”>
另外,当我更改第一个选择器项目时-第二个选择器中它也会更改...不知道为什么。
也在此处添加整个代码:
import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';
class CurrencyCashScreen extends React.Component {
state = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
base: 'PLN',
amount: '',
convertTo: 'EUR',
result: '',
date: '',
};
handleSelect = (itemValue, itemIndex) => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
handleInput = text => {
this.setState(
{
...this.state,
amount: text,
result: null,
date: null,
},
this.calculate,
);
};
calculate = () => {
const amount = this.state.amount;
if (amount === isNaN) {
return;
} else {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.state.base}`)
.then(res => res.json())
.then(data => {
const date = data.date;
const result = (data.rates[this.state.convertTo] * amount).toFixed(4);
this.setState({
...this.state,
result,
date,
});
});
}
};
handleSwap = e => {
const base = this.state.base;
const convertTo = this.state.convertTo;
e.preventDefault();
this.setState(
{
...this.state,
convertTo: base,
base: convertTo,
result: null,
},
this.calculate,
);
};
render() {
const {currencies, base, amount, convertTo, result} = this.state;
return (
<View>
<Text>
{amount} {base} is equevalent to
</Text>
<Text>
{amount === '' ? '0' : result === null ? 'Calculating...' : result}{' '}
{convertTo}
</Text>
<View>
<View>
<View>
<TextInput
keyboardType="numeric"
value={amount}
onChangeText={this.handleInput}
/>
<Picker
selectedValue={base}
value={base}
onValueChange={this.handleSelect}>
{currencies.map((currency, index) => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
<View>
<TextInput
editable={false}
value={
amount === ''
? '0'
: result === null
? 'Calculating...'
: result
}
/>
<Picker
selectedValue={convertTo}
value={convertTo}
onValueChange={this.handleSelect}>
{currencies.map(currency => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
</View>
<View>
<Text onClick={this.handleSwap}>CLICK ME</Text>
</View>
</View>
</View>
);
}
}
export default CurrencyCashScreen;
请帮助。
技术上.map()
要求在变量上执行数组。
我想.map()
不是要传递给itemValue
的数组。这就是为什么您有该错误。我认为,如果您修改代码以将handleSelect
处理为数组,则它应该可以工作。
currencies
我希望有帮助!
[很有可能不是handleSelect = itemValue => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
不是数组。这是我推荐的:
currencies
这里的任何错字都可能导致错误。const { currencies } = state;
设置为默认设置。如果在首次安装组件时currencies
未定义,则会出现此错误。currencies
,或调试器查看console.log
的值。如果在调用currencies
方法时它不是数组(包括undefined
),则将出现此错误。