我是 React Native 的新手,想要从 json 中获取嵌套对象。这是我的代码。我可以成功获取 data.phone,但如果我尝试获取 data.name.title 等,总是会得到这个。
未定义不是对象
这是我的代码。
class Dictionary extends Component {
// Initialize the hardcoded data
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
fetch('http://api.randomuser.me/?results=50')
.then((response) => response.json())
.then((responseJson) => {
//return responseJson.movies;
console.log( responseJson.results );
this.setState({
dataSource: ds.cloneWithRows(responseJson.results),
loaded:false,
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View
style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={(data) =>
<View>
<Text>
{data.phone}
</Text>
<Text>
{data.name.title}
</Text>
</View>
}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>
</View>
);
}
}
如何获取 name.title? 谢谢 这是来自 randomuser.me 的 json 数据
{"results":[{"gender":"female","name":{"title":"miss","first":"abby","last":"perkins"},"location":{"street":"9542 highfield road","city":"ely","state":"herefordshire","postcode":"J9 2ZJ"},"email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="751417170c5b0510071e1c1b0635100d14180519105b161a18" rel="noreferrer noopener nofollow">[email protected]</a>","login":{"username":"redcat541","password":"1026","salt":"LIsOByBg","md5":"2890bf50a87289f7f3664840e2c47fe3","sha1":"1944896ba6cc78ad32dcf927dc5c9226d2f9e050","sha256":"9013be19c91195788009cc545f8a2be4494687dc29b155513022ce9157b73785"},"dob":"1959-05-20 07:03:41","registered":"2006-07-10 01:28:56","phone":"0101 716 4694","cell":"0738-649-138","id":{"name":"NINO","value":"BC 35 80 42 Q"},"picture":{"large":"https://randomuser.me/api/portraits/women/54.jpg","medium":"https://randomuser.me/api/portraits/med/women/54.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/54.jpg"},"nat":"GB"}],"info":{"seed":"2e632bbc13c85cb2","results":1,"page":1,"version":"1.1"}}
当我 console.log(data.name) 时,我得到这个 {"title":"miss","first":"abby","last":"perkins"} 等等,每次迭代我都会得到不同的结果名称。所以我想 data[0] 中没有必要 - 看起来一切都可以获取正确的数据对象。只需要访问 data.name.title 但没有成功。抱歉,这次让我很困惑,因为之前每次都没有任何 json obj 或数组出现问题
最佳答案
这是由构造函数引起的,但我不知道为什么。
只需传递一个空数组即可。
this.state = {
dataSource: ds.cloneWithRows([])
};
你也可以这样做:
this.state = {
dataSource: ds.cloneWithRows([{name: "Ahmed"}])
};
请参阅此处了解更多信息: https://facebook.github.io/react-native/docs/listviewdatasource.html#clonewithrows
关于json - 如何获取 json 嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676512/