我是一个新手,正在学习React.js,并使用MVC框架和实体框架使用Visual Studio2017构建CRUD应用程序。我发现自己陷入了困境,很长一段时间都在尝试通过ajax调用控制器中的Index方法从MSSQL中的Product表中检索数据,然后在浏览器上呈现数据。
我有一个Product Table和一个Product类:
public partial class Product
{
public long Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
}
产品控制器代码为:
public class ProductsController : Controller
{
private SalesModel db = new SalesModel();
// GET: Product
public ActionResult Index()
{
return View(db.Products.ToList());
}
}
Product.jsx为:
class ProductsList extends React.Component {
constructor(props) {
super(props);
this.state = {
product: {
Id: 1,
ProductName: "Microwave",
Price: 120.90,
response: []
}
}
}
componentDidMount() {
axios.get("/Products/Index").then(response => {
//console.log(response.data);
this.setState({
product: Object.assign({}, this.state.product, { response: response.data })
});
});
}
render() {
return (
<section>
<h1>Products List</h1>
<div>
<table>
<thead><tr><th>Product Id</th><th>Product Name</th>
<th>Product Price</th></tr></thead>
<tbody>
{
this.state.product.response.map((item, key) => {
return <tr key={key}><td>{item.Id}</td><td>
{item.ProductName}</td><td>{item.Price}</td></tr>;
})
}
</tbody>
</table>
</div>
</section>
)
}
}
ReactDOM.render(<ProductsList/>,document.getElementById('myContainer'));
视图为:
@using System.Web.Optimization
@model IEnumerable<MarsOnBoardTasks.ViewModels.Product>
@{
ViewBag.Title = "Index";
}
<html>
<body>
<h2>Index</h2>
<div id="myContainer" class="container">
</div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
@* Jquery *@
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
@* React Library *@
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-
dom.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
@* ReactJS components *@
@*<script src="/Scripts/Product.jsx"></script>*@
@Scripts.Render("~/Scripts/React/Product.jsx")
发布于 2018-08-16 11:10:04
确保您的响应是一个数组。.maps只适用于数组,不适用于对象使用Object.entries().it会将对象的键和值放入数组中,
{"a":1} => [0]="a",[1]=1
Object.entries(this.state.product).map((product)=>{})
发布于 2018-08-16 14:27:09
请在Reactjs中阅读更多关于Life cycle
的信息。
在render(){
函数之后运行componentDidMount
。当使用this.state.product.response.map
状态未设置且为空时。
https://stackoverflow.com/questions/51868359
复制相似问题