我构建了一个反应本机组件,可让您选择几种类型的啤酒,并将其渲染到picker的列表视图中。
我遇到的问题是将数据发送到BreweryDB API中。我不确定该半完整组件从哪里开始。
import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet, ListView } from 'react-native'
const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
export default class BeerPicker extends Component {
constructor(props){
super(props);
this.state = {
beer: [],
beerDataSource: ds.cloneWithRows([]),
dataSource: ds.cloneWithRows(['string1', 'string2', 'string3']), //It seems to be not needed...
items: [
{label: 'Choose Beer', value: 'none'},
{label: 'IPA', value: 'ipa'},
{label: 'Pilsner', value: 'pilsner'},
{label: 'Stout', value: 'stout'}
],
selectedItem: 'none'
};
this.addBeer = this.addBeer.bind(this);
}
addBeer(itemValue, itemIndex){
let newBeerArray = [...this.state.beer, itemValue];
this.setState({
beer: newBeerArray,
selectedItem: itemValue,
beerDataSource: ds.cloneWithRows(newBeerArray),
});
}
renderRow(data) {
return (
<Text>{`u2022 ${data}`}</Text>
);
}
render() {
let items = this.state.items.map((item, index) => {
return (<Picker.item label={item.label} value={item.value} key={index}/>);
});
return (
<View>
<Picker selectedValue={this.state.selectedItem} onValueChange = {this.addBeer}>
{items}
</Picker>
<ListView
dataSource={this.state.beerDataSource}
renderRow={this.renderRow}/>
</View>
)
}
}
const styles = StyleSheet.create({
text: {
fontSize: 30,
alignSelf: 'center',
color: 'black'
}
});
我想使用每个选定的项目并多次循环通过API循环以获取有关每个选项项目的信息。
您可以做几种方法。如果您想在用户选择新啤酒时进行API调用,则以下代码可能会有所帮助:
将apiData: {}
添加到初始状态
在Addbeer函数中添加this.fetchBeerFromApi(itemValue);
// notice I used es7 fat arrow functions to avoid having to bind in constructor
fetchBeerFromApi = async (beerId) => {
let response = await fetch(`${BREWERY_API_URL}/beer/${beerId}`);
response = await response.json();
if (response.error) {
console.error('Error with brewery api beer request', response.error);
return false;
}
const apiData = this.state.apiData;
apiData[beerId] = response;
// Or handle storing apiData somewhere else... I usually use immutable data
// structures to avoid deeply nested data not triggering re-rendering issues
// so this may or may not be problematic...
// Here is the immutablejs alternative to those last two lines:
// const apiData = this.state.apiData.set(beerId, response);
// Here we store it back to state where you can handle rendering the data if
// it is available
this.setState({apiData});
}