【发布时间】:2018-05-20 19:16:32
【问题描述】:
我在尝试解析此 JSON 数据时遇到问题。我可以通过将我的数据限制为这样的一个来修复这个错误:{"id": "13", "imagename": "hello"},但这是我的全部数据:
{"id":"1","imagename":"dog"}{"id":"2","imagename":"cat"}{"id":"3","imagename":"mouse"}{"id":"4","imagename":"deer"}{"id":"5","imagename":"shark"}{"id":"6","imagename":"ant"}
我认为 React Native 只能处理 <Text> 中的一个数据?
export default class HomeScreen extends React.PureComponent {
constructor(props)
{
super(props);
this.state = {
isLoading: true,
};
componentDidMount(){
fetch(`http://www.example.com/React/data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
data = responseJson;
this.setState({ loading: false });
}).catch((error) => {
console.warn(error);
});
}
renderItems() {
const items = [];
this.data.foreach( ( dataItem ) => {
items.put( <Text>{ dataItem.id }</Text> );
} )
return items;
} <--- This is an attempt to try to put them in an object and then display the data, but I keep getting undefined.
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{this.data.id}</Text>
<Text>{this.data.imagename}</Text>
</View>
</Card>
</View>
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
flex:1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#333',
},
}
我还查找了其他解析错误问题,但我们的代码非常不同。正如我之前所说,如果数据限制为一个,则此代码有效。我不明白为什么它不允许显示多个数据。
编辑:当我将response.json 更改为文本时,我没有得到任何结果,所以这可能是一个原因。当我将 <Text>{this.data.id}</Text> 更改为 this.data 时,我可以看到所有数据。如何仅从该数据中获取 id?
【问题讨论】:
-
可能是因为你的对象没有用逗号分隔,也没有放在数组中。
-
您确定您的 JSON 格式正确吗?您提供的不是数组或用逗号分隔。
-
@TobyOkeke 我也这么想,我试过了:
this.data = responseJson.join(', ');。这仍然没有解决错误。 -
@AnthonySherratt 我相信是这样,当我将所有数据限制为一组时,它确实会显示出来。但是一个错误不止一个。
-
加入后应该是一个csv字符串。你把它做成数组了吗?
标签: arrays json reactjs object react-native