0
試圖通過讀取JSON數據來執行自動完成建議。在JSON中訪問數組內部的數組React-Native
JSON數據的格式是:
locations: [ { "Companyname": "pqr", "TopfiveproductsList": [ { "prodId": "16", "prodName": "abc" }, { "prodId": "17", "prodName": "xyz" } ], "companycode": "C1" }, { "Companyname": "zzz", "TopfiveproductsList": [ { "prodId": "12", "prodName": "yyy" }, { "prodId": "14", "prodName": "lmn" }, { "prodId": "32", "prodName": "qaq" } ], "companycode": "C2" } ]
顯示從
locations
陣列和TopfiveproductsList
陣列的其相應的記錄companyname
。
在下面的代碼中顯示companyname
,但不顯示其相應的TopfiveproductsList.prodName
。訪問
prodName
給出錯誤JSON parse error: Unexpected identifier object
。<Autocomplete autoCapitalize="none" autoCorrect={false} data={locations} defaultValue={query} onChangeText={text => this.setState({ query: text })} renderItem={({ Companyname, TopfiveproductsList.prodName }) => ( <Text>{Companyname} {TopfiveproductsList.prodName}</Text )} />
index.android.js
import Sample from './sample.json';
export default class pre extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
query: '',
};
}
loadData() {
this.setState({ locations : Sample });
}
findLocation(query) {
this.loadData();
const { locations } = this.state;
const regex = new RegExp(`${query.trim()}`, 'i');
return locations.filter(location => location.Companyname.search(regex) >= 0);
}
render() {
const { query } = this.state;
const locations = this.findLocation(query);
return (
<View>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
data={locations}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
renderItem={({ Companyname }) => (
<Text> {Companyname} </Text>)}
/>
</View>
);
}
}
提示錯誤'r.render():有效的做出反應元素(或空)必須歸還。你可能已經返回undefined,一個數組或其他一些無效的對象。' – Akki
哦,我的壞,你必須改變它'返回 ... ',我只是更新了我的答案 –
謝謝。我也想添加ToucableOpacity。我試着做這個'返回 this.setState({query:Companyname})}> \t {公司名稱} {prodNames} TouchableOpacity>}'但它給出了錯誤'rawtext必須是包裹在明確的組件' –
Akki