我正在尝试使用ComponentDidMount从数据库中获取数据,这是我的代码
class ExistingWorkouts extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('mount')
fetch('http://localhost:3000/getworkouts')
.then(response => response.json())
.then(data => console.log(data))
}
render() {
return (
<div className='existing-container'>
<h5>Back and Biceps</h5>
<h6>4 exercises</h6>
</div>
)
}
}
export default ExistingWorkouts;
这是我的后端代码
app.get('/getworkouts', (req, res) => {
db.select('*').from('routines')
.where('userid', '=', user.id)
.then(data => {
res.status(200).json(data)
})
.catch(err => status(400).json("Error getting workouts"))
})
加载我的应用程序时,后端发送的数据被发送了15次,这意味着ComponentDidMount运行了15次,我不明白为什么会这样
答案 0 :(得分:0)
好吧,我已经意识到为什么会发生这种愚蠢的错误。组件ExistingWorkouts
由其父组件渲染15次,因此ComponentDidMount运行15次。所以我必须在父组件而不是子组件中使用ComponentDidMount