json - React-Native render json from fetch
问题描述
I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.
I have set the state as follows:
this.state = {
loading: true,
file: null,
video: null,
marks: []
};
and my fetch:
componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
this.setState({
loading: false,
marks: data.mark
}, () => {
console.log(data.mark);
console.log(this.state.marks);
// const dataMap = data.mark.map((item) => {
// return {
// key: item.id,
// label: item.mark
// };
// });
});
})
.catch(err => console.log(err));
}
Now my render inside of the return:
const { marks } = this.state;
<FlatList
data={marks}
renderItem={({ item }) => <Text>{item.mark}</Text>}
keyExtractor={(item, index) => index}
/>
Do I have to map the data then try to render it??
OUTPUT OF console.log(this.state.marks):
{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }
The mark is a pseudorandom string that can contain letters and numbers created on the backend
解决方案
因为 this.state.marks 是一个对象。首先,您需要将其转换为这种形式 [{}]。您可以进行以下更改以使其正常工作。
fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
let marks = [data.mark]; //Add this line
this.setState({
loading: false,
marks: marks // Change this line
}, () => {
....
Rest of your code
推荐阅读
- nginx - Nginx。将 https 请求限制在一个域
- python - python中的SVM(支持向量机)总是给出相同的预测
- r - 使用 na.locf 为特定国家/变量对扩展最后观察到的值
- php - 使用 GET 方法为集合创建自定义路由
- java - Java:如何在“常规” TCP Socket 和 SSLSocket 之间进行抽象
- php - Mysql+PHP中的2步过滤
- android - Ionic4 构建安卓
- html - 我可以做些什么来阻止从输入单选更改值属性?
- scala - 我如何理解 Spark 中使用了缓存?
- c# - 如何创建 .net 标准和 .net 框架自包含构建?