在下面的代碼中,我必須使用選擇器。我想從 API 中增加價值。我從 API 獲得了值,但它沒有反映在選擇器值上,請幫助我解決這個問題。我知道這是一個小錯誤,但我是 react-native 的新手,很抱歉這個愚蠢的問題。
import React, { Component, useState } from "react";
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Picker } from "@react-native-picker/picker";
import { PickerItem } from "react-native/Libraries/Components/Picker/Picker";
class VolunteerPage extends Component {
constructor(props) {
super(props);
this.state = ({
stateList: []
});
}
componentWillMount() {
this.getdata();
}
getdata() {
var temp = [];
const url = "https:www.example.com";
fetch(url, {
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'})
})
.then(res => res.json())
.catch(error => console.error('Error : ', error))
.then((response) => {
console.log("Response : ",response);
var length = response.state.length;
console.log("Length of State is : ",length);
if (length > 0) {
for (let i = 0; i < length; i ) {
var data = response.state[i];
var joined = { value: data.amd_state };
temp.push(joined);
}
}
this.setState({
stateList: temp
});
})
}
render() {
return (
<View>
<Picker} onValueChange={(itemValue,
itemIndex)=>this.setState((stateList.itemValue))}>
<Picker.Item label="Select State" value="this.state.stateList" />
</Picker>
<TouchableOpacity style={styles.TouchableOpacity} onPress={() => this.apiCallHere()}>
<Text style={{ color: "white" }}>Next</Text>
</TouchableOpacity>
</View>
)
}
}
export default VolunteerPage
uj5u.com熱心網友回復:
我認為你的錯誤在這里:
<Picker}
onValueChange={
(itemValue,itemIndex)=>
this.setState((stateList.itemValue)_
}
>
<Picker.Item label="Select State" value="this.state.stateList" />
</Picker>
我想你希望它是:
<Picker
onValueChange={ (itemValue,itemIndex)=>
this.setState({stateList:itemValue})
)}
>
<Picker.Item label="Select State" value={this.state.stateList} />
</Picker>
uj5u.com熱心網友回復:
抱歉,在您呼叫 api 之后,我真的不明白狀態串列發生了什么。我會為您的狀態添加一個附加值,selectedIndex以跟蹤當前選擇的內容。所以你的建構式看起來像
constructor(props) {
super(props);
this.state = {
stateList: [],
// -1 or default selection value
selectedIndex:-1
};
}
然后利用陣列類的 map 函式來呈現所有 stateList 選項:
<Picker
onValueChange={ (itemValue,itemIndex)=>
this.setState({selectedIndex:itemIndex})
)}
>
{this.state.stateList.map( (value,index)=> (
<Picker.Item
{/*
Here I use a generic name, but you could use the
value of the value if you wish
*/}
label={"Option " (index 1)}
value={value}
/>
)}
</Picker>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/318430.html
