reactjs - react-native AJAX&API - 渲染 JSON 数据
问题描述
我真的是新手反应。我的问题是如何迭代组件并呈现 json 数据。这是我的代码:
import React from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { Divider } from 'react-native-elements';
import { limitUI04 } from 'uuid-js';
export default class SearchProperty extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
}
}
componentDidMount() {
fetch("myapiendpoint", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.data
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
{
items.map(key => {
return (
<Text>
{key.id}
</Text>
)
})
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
我上面的代码返回错误:
不变违规:不变违规:SearchProperty(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。
请帮忙
解决方案
你错过了之后的退货声明render
render() {
const { error, isLoaded, items } = this.state;
return (
<div>
{
items.map(key => {
return (
<Text key={key.id}>
{key.id}
</Text>
)
})
}
</div>
}
)
}
那应该很好去。
注意:请记住,当您映射某些东西时,map 函数的返回语句中的最外层元素或根元素必须包含唯一键。由于我假设您key.id
是独一无二的,因此您可以将其用作您的唯一密钥。
更新答案:
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
class App extends Component {
state = {
error: null,
isLoaded: false,
items: [
{ id: 1, name: "Apples", price: "$2" },
{ id: 2, name: "Peaches", price: "$5" }
]
};
componentWillMount() {
this.setState({ items: [...this.state.items, { id: 3 }] }, () => {
this.displayItems(this.state.items);
});
}
displayItems = items => {
console.log(items);
return items.map(key => {
return <div key={key.id}>{key.id}</div>;
});
};
render() {
const { items } = this.state;
return <div>{this.displayItems(items)}</div>;
}
}
export default App;
我将 didMount 更改为 WillMount()。WillMount() 将在渲染任何内容之前挂载(双关语不是有意的)。然后组件将渲染地图功能。所以状态被更新了。我将项目从 WillMount() 发送到新函数 displayItems 以额外确保状态将更新。希望这可以帮助。
编辑:警告
我在这里使用了 WillMount() 但我没有包括 UNSAFE。componentWillMount()
版本 17 之后将不再工作。您可以使用UNSAFE_componentWillMount()
. 这将适用于版本 17。对此感到抱歉(我习惯于从 IntelliSense 中选择它)。
推荐阅读
- c# - how to get records from db having one common column values with another list?
- html - W3C 支持的滚动条自定义
- javascript - 带有类别列表中字典数组的 JS Autobuild 表
- solr - Solr 7.2.1 中的非法 group.format 参数
- vue.js - why axios get method request send twice?
- c# - 如何将数据从一个场景传递到另一个场景?
- angular - 从组件到组件的单击事件
- java - 如何从左到右跟踪和移动字符串?
- javascript - Javascript - 每次客户进入商店时弹出
- android - 在颤振中完成后执行for循环