如何解决传递道具 React (Typescript) .Net 核心
我试图将一个 Id(我猜可以看作是一种状态)从一个组件传递到另一个
在组件主页中:
interface FetchDataExampleState {
games: Games[];
loading: boolean;
}
interface Games {
g_Id: number;
g_Title: string;
g_Genre: string;
g_Plattform: string;
g_ReleaseDate: Date;
g_Price: number;
}
我得到了两个接口,我想从中传递 g_Id 以在 EditGame 中使用
我的放置 API:
[HttpPut("{id}")]
[Route("EditGame")]
public async Task<IActionResult> PutGame([Fromroute] int id,[FromBody] Game game)
{
game.G_Id = id;
_context.Entry(game).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (dbupdateConcurrencyException)
{
if (!GameExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
尝试在 EditGame 组件中使用的获取:
handleClick = (e: any) => {
console.log("Hello");
fetch("api/Games/EditGame",{
method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({
g_Title: this.state.g_Title,g_Genre: this.state.g_Genre,g_Plattform: this.state.g_Plattform,g_ReleaseDate: this.state.g_ReleaseDate,g_Price: this.state.g_Price,})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
g_Title: data.g_Title,g_Genre: data.g_Genre,g_Plattform: data.g_Plattform,g_ReleaseDate: data.g_ReleaseDate,g_Price: data.g_Price,});
let path = '/Home';
this.props.history.push(path);
});
}
我的路线:
<Route path='/Home' component={Home} />
<Route path='/EditGame' component={EditGame} />
我尝试查找并尝试了所有热门结果,包括:
- Github
- How to pass props to route in react router v5 with Typescript?
- Pass component props in Private Route with Typescript and React
- Pass props through react router link typescript
我不确定我是否遗漏了什么,因为我是新手,或者我做错了什么。 感谢您的帮助:)
解决方法
尝试使用 React 函数式组件
或者更像是基于我的经验。
<Route path='/EditGame/:id' component={EditGame} />
props.match.params.id
,所以经过长时间的搜索,我能够解决它如下
<li><Link to={{ pathname: "/EditGame",state: { id: games.g_Id,title: games.g_Title,genre: games.g_Genre,Plattform: games.g_Plattform,rdate: games.g_ReleaseDate,price: games.g_Price } }} >Edit</Link></li>
通过从家中调用值并将它们通过状态传递到 EditGame,在那里我在 fitch 方法中这样调用它们
handleClick = (e: any) => {
console.log("Hello");
fetch("api/Games/EditGame",{
method: 'PUT' + this.props.location.state.id,headers: { 'Content-Type': 'application/json' },body: JSON.stringify({
g_Id: this.props.location.state.id,g_Title: this.props.location.state.title,g_Genre: this.props.location.state.genre,g_Plattform: this.props.location.state.Plattform,g_ReleaseDate: this.props.location.state.rdate,g_Price: this.props.location.state.price,})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
g_Title: data.g_Title,g_Genre: data.g_Genre,g_Plattform: data.g_Plattform,g_ReleaseDate: data.g_ReleaseDate,g_Price: data.g_Price,});
let path = '/Home';
this.props.history.push(path);
});
}
现在这可能不是最好的方法,但效果很好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。