我正在 react-native 中处理一个项目,在那里我很难通过将对象数组中的元素作为我希望使用它的道具传递来访问对象数组中的元素。要求是获取 name 属性并将其设置为平面列表中的文本。
我的对象数组的结构如下。
[
{
"media1":[
{"name":"Lynn"},
{"name":"Michelle"},
{"name":"Carter"}
]
},
{
"media2":[
{"price":"23"},
{"price":"76"},
{"price":"39"}
]
}
]
这就是如何将此对象数组作为道具传递到我希望使用它的地方
return (
<View>
<AlbumDetail data = {this.state.allData}/>
</View>
);
这就是我希望使用它的地方
const AlbumDetail = (props) => {
return (
<View>
{console.log(props.data[0])} //Working
{console.log(props.data[0].media1[0].name)} //Not working
// Requirement as bellow
<Text>{wants to set the "name" here}</Text>
<Text>{wants to set the "price" here}</Text>
</View>
);
};
我怎样才能做到这一点??
您可能希望放置两个缺少的逗号。一个之后:
{"name":"Michelle"}
一个之后
{"price":"76"}
- AlbumDetail无法知道它有一个名为data的属性。您需要将 AlbumDetail 函数编写为 React.Component 类。
- 你正在将一个JSON对象传递到AlbumDetail中,你需要在使用它之前调用JSON.parse(data(。更新:
.then(resp => resp.json())
用于解析 json。 - 在返回之前放置控制台.log。返回的对象应该是纯 JSX 组件。
下面的代码应该可以解决您的问题:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const url =
'http://purelight-prod.appspot.com/api/user/v2/browse/homescreendata';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: undefined,
};
}
componentDidMount() {
fetch(url)
.then(resp => resp.json())
.then(respJson => {
this.setState({
data: respJson,
});
})
.catch(err => {
console.error(err);
});
}
render() {
return (
<View style={{ flex: 1 }}>
<TestView data={this.state.data} />
</View>
);
}
}
class TestView extends React.Component {
render() {
!!this.props.data && console.log(console.log(data[0].healer[0].healerid));
return (
<View>
<Text>Hello World!</Text>
</View>
);
}
}
编辑:
使用 componentDidMount()
,因为我们喜欢显示某些内容(加载图标等(,然后在数据到达时更新视图。
这是一个异步任务。数据必须保留,直到到达。我使用 !!this.props.data && ...
,所以它只在未定义时才显示。
由于 API 响应是一个相对较大的包,因此如果您使用 TypeScript 并创建一个对象类来解析它,它将更容易使用。
我不认为 API 帮助程序包在您的代码中提供正确的响应。