我在从 api 获取数据进行反应时遇到问题,我认为存在逻辑错误,你能帮我吗?我不认为我在后端的 Visual Studio 上有任何错误,因为它在 Postman 上运行良好,但在 Visual Studio Code 中我有这个问题。 此外,我正在使用 .net core 5.0,我正在关注的视频使用 3.1。 我的代码是这样的: .env 文件:
REACT_APP_API=http://localhost:53535/api/
REACT_APP_PHOTOPATH=http://localhost:53535/Photos/
.Positions.js
import React,{Component} from 'react';
import {Table} from 'react-bootstrap';
import {Button,ButtonToolbar} from 'react-bootstrap';
import {AddPosModal} from './AddPosModal';
export class Positions extends Component{
constructor(props){
super(props);
this.state={deps:[], addModalShow:false}
}
refreshList(){
fetch(process.env.REACT_APP_API+'positions')
.then(response=>response.json())
.then(data=>{
this.setState({deps:data});
});
}
componentDidMount(){
this.refreshList();
}
componentDidUpdate(){
this.refreshList();
}
render(){
const {deps}=this.state;
let addModalClose=()=>this.setState({addModalShow:false});
return(
<div>
<Table className="at-4" striped bordered hover size="sm">
<thead>
<tr>
<th>PositionID</th>
<th>Position</th>
<th>Options</th>
</tr>
</thead>
<tbody>
{deps.map(pos=>
<tr key={pos.PositionID}>
<td>{pos.PositionID}</td>
<td>{pos.Position}</td>
<td>Edit / Delete</td>
</tr>)}
</tbody>
</Table>
<ButtonToolbar>
<Button variant='primary'
onClick={()=>this.setState({addModalShow:true})}>
Add Position
</Button>
<AddPosModal show={this.state.addModalShow}
onHide={addModalClose}></AddPosModal>
</ButtonToolbar>
</div>
)
}
}
答案 0 :(得分:1)
处理不同 api 端点时的潜在错误在以下函数中。正如评论者所解释的,这不是导致此错误的原因,如果您稍后必须处理不同的端点,请参阅这是一个干净的代码最佳实践:) 功能:
refreshList(){
fetch(process.env.REACT_APP_API+'positions')
“positions”是一个静态字符串,而不是字符串类型的动态变量。
它应该是这样的(在 Typescript 中):
refreshList(thePosition: string){
fetch(process.env.REACT_APP_API + thePosition)