我是一个非常新手,学习React.js并使用MVC框架和Entity框架使用Visual Studio 2017构建CRUD应用程序。我发现自己陷入了一个困境,并且试图在MSSQL中通过对控制器中Index方法的ajax调用从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")
答案 0 :(得分:1)
确保您的响应是一个数组。 .maps仅适用于数组,不适用于对象 使用Object.entries()。它将使对象的键和值成为数组,
{"a":1} => [0]="a",[1]=1
Object.entries(this.state.product).map((product)=>{})
答案 1 :(得分:0)
请在Reactjs中详细了解Life cycle
。
componentDidMount
在render(){
函数之后运行。
使用this.state.product.response.map
时未设置状态,并且为空。