我正在使用React Native Picker。
我正在调用一个返回State
和列表的 API 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 时,Picker 会加载所有State
和City
.
但是,无论如何我可以过滤
State
和City
我只想City
根据State
所选内容显示的地方吗?即如果我选择
state: 14
,选择器应该只显示city: 262
和city: 263
或者如果我选择
state: 10
,选择器应该只显示city: 256
重要说明:目前
State
数据中只有两个,但将来我将添加多个State
,每个都包含多个City
。例如:state: A
将有 5 个城市,state: B
将有 3 个城市等。
请让我知道是否有任何City
基于State
选定的有效过滤方式,并且一如既往地所有帮助将不胜感激。
下面提供的代码片段:
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>
);
}
}
应用程序截图: