为什么 material-ui-lab 评级组件有时会发送 null onChange?

时间:2021-05-18 20:54:00

标签: reactjs react-redux material-ui

刚开始使用 material-ui,我在输入 @material-ui/lab/Rating 时遇到问题。有时,当我尝试连续多次单击评级组件时,传递给我的控制器的值返回 null 而不是我单击的评级。以下是在我的控制器中记录传入数据后的控制台:

Rating Passed: 5
id:  60a42672c615650cb85629f4
Rating Passed: null
id:  60a42672c615650cb85629f4
Rating Passed: 4
id:  60a42672c615650cb85629f4

来自我的前端的片段:

<CardActions className={classes.cardActions}>
        <Rating name={post._id} value={post.raters !== 0 ? post.rating/post.raters : 0} precision={1} max={5} onChange={(event, v)=>{dispatch(ratePost(post._id , {rating: v}))}}/>
</CardActions>

如果相关,我的控制器:

export const ratePost = async (req, res) => {
    try {
        console.log("Rating Passed: ", req.body.rating);
        const { id: _id } = req.params;
        console.log("id: ", _id);
        if(!mongoose.Types.ObjectId.isValid(_id)) {
            return res.status(404).send('Post to rate not found');
        }

        const post = await PostMessage.findById(_id);
        let newRaters = post.raters + 1;
        let newRating = (post.rating + req.body.rating);
        if(req.body.rating === null) {
            newRaters = post.raters;
            newRating = post.rating;
        }

        const updatedPost = await PostMessage.findByIdAndUpdate(_id, {rating: newRating, raters: newRaters}, {new:true});
        res.json(updatedPost);
    } catch (error) {
        console.error(error);
    }
}

目前,在我的控制器中,我只是忽略空输入。但是,当未注册评级点击时,它会使网站感觉没有响应。什么可能导致评级组件发送空值?

0 个答案:

没有答案