【问题标题】:ComponentDidMount called lots of timesComponentDidMount 调用了很多次
【发布时间】:2020-07-23 17:40:50
【问题描述】:

我正在尝试使用 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"))
})

当我的 react 应用加载时,我后端的数据被发送了 15 次,这意味着 ComponentDidMount 运行了 15 次,我不明白为什么会这样

【问题讨论】:

    标签: node.js reactjs api


    【解决方案1】:

    好的,我已经意识到为什么会发生这种情况,这是一个愚蠢的错误。组件ExistingWorkouts 被其父组件渲染了 15 次,因此 ComponentDidMount 运行了 15 次。所以我必须在父组件中使用 ComponentDidMount 而不是子组件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多