我正在使用React Native Picker。
我调用了一个API,它返回一个State
和City
列表。
目前有两个
State
:Kuala Lumpur
(state: 14
) 和Selangor
(state: 10
)
state: 14
有两个City
:Kuala Lumpur
(city: 262
) 和Sungai Besi
(city: 263
)
state: 10
有一个City
:Puchong
(city: 256
)
JSON数据如下:
{
"data": [
{
"city": "262",
"state": "14",
"city_desc": "Kuala Lumpur",
"state_desc": "Kuala Lumpur"
},
{
"city": "263",
"state": "14",
"city_desc": "Sungai Besi",
"state_desc": "Kuala Lumpur"
},
{
"city": "256",
"state": "10",
"city_desc": "Puchong",
"state_desc": "Selangor"
}
]
}
在我的应用程序中,当我调用API时,选择器会加载所有的
State
和City
。然而,是否有办法过滤
State
和City
,只显示基于所选State
的City
?例如:如果我选择
state: 14
,那么选择器应该仅显示city: 262
和city: 263
。或者如果我选择
state: 10
,那么选择器应该仅显示city: 256
。重要提示:目前数据中只有两个
State
,但将来我将添加多个State
,每个州都包含多个City
。例如:state: A
将拥有5个城市,state: B
将拥有3个城市等等。请告诉我是否有任何高效的方法可以根据所选的
State
筛选City
,如常,非常感谢所有帮助。以下是提供的代码片段:
class ClientScreen extends Component {
constructor(props) {
super(props);
this.state = {
pickerValueState: null,
dataState: [],
pickerValueCity: null,
dataCity: [],
isLoading: true,
}
}
componentDidMount() {
console.log('ComponentDidMount()');
this.apiStateCity();
}
apiStateCity() {
let self = this;
AsyncStorage.getItem('my_token').then((keyValue) => {
axios({
method: 'get',
url: Constants.API_URL + 'user_c/c_State_City/',
responseType: 'json',
headers: {
'X-API-KEY': Constants.API_KEY,
'Authorization': keyValue,
},
})
.then(function (response) {
console.log('apiStateCity Response: ', response.data.data);
self.setState({
dataState: response.data.data,
});
})
.catch(function (error) {
console.log('Error (1st): ', error);
});
}, (error) => {
console.log('Error (2nd): ', error) //Display error
});
}
stateList() {
return (
<View>
<Text>Select Location</Text>
<Text>State</Text>
<View>
<Picker
mode="dropdown"
selectedValue={this.state.pickerValueState}
onValueChange={(itemValue, itemIndex) => {
this.setState({ pickerValueState: itemValue });
console.log('State selected (itemValue): ', itemValue);
}}
>
{
this.state.dataState.map((item, key) => (
<Picker.Item label={item.state_desc} value={item.state} key={key} />)
)
}
</Picker>
</View>
</View>
);
}
cityList() {
return (
<View>
<Text>City</Text>
<View>
<Picker
mode="dropdown"
selectedValue={this.state.pickerValueCity}
onValueChange={(itemValue, itemIndex) => {
this.setState({ pickerValueCity: itemValue });
console.log('City selected (itemValue): ', itemValue);
}}
>
{
this.state.dataState.map((item, key) => (
<Picker.Item label={item.city_desc} value={item.city} key={key} />)
)
}
</Picker>
</View>
</View>
);
}
render() {
return (
<View>
<Text>BookingApp</Text>
<View>
{this.stateList()}
{this.cityList()}
{this.button()}
</View>
</View>
);
}
}
应用程序截图: