我是新来的本地人,我有一个问题。首先,我将解释我的工作。我有一个数组对象最初具有一些值。 componentWillMount函数将从json格式的数据库中获取值。我解析该json以存储在我的对象数组中。之后,我想在选择器列表标签中看到该值。
问题是我的选择器列表中仅显示初始值。我需要从数据库解析值存储数组对象之后显示一个值。
这是我的代码
constructor(props){
super(props);
this.state = {
a: [{"id": 0, "windID": "1", "windname": "a"},],
windFormID:'',
}
}
componentWillMount(){
return fetch('http://api.kiot.katomaran.com/api/v1/wind_farms', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === true){
for ( i = 0,len = responseJson.data.length ; i < len; i++) {
if(i===0)
{
this.state.a[0]={'id':i,'windID' : responseJson.data[i].id,'windname' : responseJson.data[i].name}
}
else{
this.state.a.push({'id':i,'windID' : responseJson.data[i].id,'windname' : responseJson.data[i].name})
}
}
console.log(this.state.a)
}
else{
alert(responseJson.message);
}
})
}
<Picker
selectedValue={this.state.windFormID}
style={styles.button}
onValueChange={(itemValue, itemIndex) =>
this.setState({windFormID: itemValue})}>
{this.state.a.map((key, index) => {
return(<Picker.Item label={key.windname} value={index} key=
{index}/>)
})}
</Picker>
昨天有人帮助我解决了这个问题。但这不会有任何问题。 我完全被困在这里两天了……
答案 0 :(得分:1)
使用setState
doc
let newarray=[];
for ( i = 0,len = responseJson.data.length ; i < len; i++) {
newarray.push({'id':i,'windID' : responseJson.data[i].id,'windname' : responseJson.data[i].name})
}
this.setState({a:newarray})