我想在名为Panel
的react组件中为登录用户获取商店详细信息
如果该用户的商店存在,它应该显示详细信息,否则应该显示一条消息。
这是面板反应组件:
import React, {useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import CircularProgress from '@material-ui/core/CircularProgress';
import axios from "axios";
import config from 'config';
const url = `${config.apiUrl}/api/Shops`
export const Panel=()=> {
const [loading, setLoading] = useState(true);
const[shop,setShop]=useState(undefined);
const user=JSON.parse(localStorage.getItem('user'))
useEffect(()=>{
axios.get(url + `userId=${user.id}`).then((res)=>{
setShop(res.data);
} );
setTimeout(()=>{
setLoading(false);
},1000)
},[]);
console.log("shop",shop);
//
return (
<div>
{loading === true ? (<CircularProgress />): (
<div>
<h2> Dashboard</h2>
{shop[0]!=undefined ? <h3>{shop[0].storeName}</h3>:<h3>No Details Found</h3>}
</div>
)
}
</div>
);
}
这是Shop
型号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApi.Models
{
public class Shop
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[StringLength(150)]
public string StoreName { get; set; }
[DataType(DataType.MultilineText)]
public string Details { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public DateTime UpdatedOn { get; set; }
}
}
这是控制器-通过Id:购物
// GET: api/Shops/5
[HttpGet("{id}")]
public async Task<ActionResult<Shop>> GetShop(int id)
{
var shop = await _context.Shops.FindAsync(id);
if (shop == null)
{
return NotFound();
}
return shop;
}
这是Get Shop By userId:
// GET: api/Shops/5
[HttpGet("{userId}")]
public async Task<ActionResult<Shop>> Panel(int userId)
{
var shop = await _context.Shops.FindAsync(userId);
if (shop == null)
{
return NotFound();
}
return shop;
}
问题是,我想用userId而不是id来获取商店,因为我们只有userId
,我们可以基于它来获取商店。我们没有id
商店。
此外,如果我的axios调用中有问题,也可以帮助解决。
提前谢谢。
我的应用程序使用前端的react+节点和作为后端的asp.net web api。
如果您想通过userId获取商店数据,请修改您的代码,如下所示:
var shop = await _context.Shops.FirstOrDefaultAsync(a=>a.UserId==userId);