我一直在尝试使用fetch api来显示json并使用map来迭代数据,但我一直在显示json并在reactjs中迭代它
这是文件
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super();
this.state = {
productlist: [],
error: null,
}
}
componentDidMount(){
fetch(`http://texpertise.in/data.php`)
.then(result => result.json())
.then(productlist => this.setState({productlist: productlist.value}))
}
render() {
return (
<div>
{this.state.productlist.map(product =>
<div> {product.name} </div>
<div> {product.description} </div>
<div> {product.image} </div>
<div> {product.nonVeg} </div>
<div> {product.spicy} </div>
)}
</div>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
我收到此错误
./ SRC / App.js
Syntax error: reactspa/src/App.js: Adjacent JSX elements must be wrapped in an enclosing tag (42:23)
40 | {this.state.productlist.map(product =>
41 | <div> {product.name} </div>
> 42 | <div> {product.description} </div>
| ^
43 | <div> {product.image} </div>
44 | <div> {product.nonVeg} </div>
45 | <div> {product.spicy} </div>
答案 0 :(得分:1)
使用react 15.1时,你的.map只返回一个元素,在你的情况下,你正在返回
<div>{product.name}</div> <div>{product.description}</div>
它应该被包装并作为单个元素返回
<div><div>{product.name}</div> <div>{product.description}</div></div>