You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore空值问题:点击图片后无法将情绪值存入Firestore

问题分析与解决方案

你的代码核心问题是点击图片按钮时没有更新feeling状态变量,导致提交到Firestore时feeling始终是初始空值。下面是具体修复步骤:

1. 新增情绪点击处理函数,更新状态

删除原有的handleSubmit函数,替换为直接更新feeling状态的逻辑:

const handleFeelingClick = (value) => {
  setFeeling(value);
};

2. 修改按钮的点击事件绑定

给每个情绪按钮绑定上述函数,传入对应的情绪值:

<Button value="Good" onClick={() => handleFeelingClick("Good")}>
  <CardMedia
    component="img"
    height="50"
    image={Good}
    alt="Feeling awesome"
  />
</Button>
<Button value="Neutral" onClick={() => handleFeelingClick("Neutral")}>
  <CardMedia
    component="img"
    height="50"
    image={Neutral}
    alt="Feeling Neutral"
  />
</Button>
<Button value="Bad" onClick={() => handleFeelingClick("Bad")}>
  <CardMedia
    component="img"
    height="50"
    image={Bad}
    alt="Feeling Bad"
  />
</Button>

注意:移除CardMedia上无用的value={feeling}属性,该属性不会对状态更新产生作用。

3. 优化提交函数的异步逻辑(可选)

原handleAdd函数混用await和.then(),统一为async/await写法更清晰规范:

const handleAdd = async () => {
  try {
    await addDoc(postsCollectionRef, {
      feeling,
      postText,
      date: new Date().toISOString(), // 使用ISO标准格式日期更便于后续查询
      author: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
    });
    alert("publicación subida");
    navigate("/home");
  } catch (error) {
    alert(error.message);
  }
};

4. 移除提交按钮的重复事件绑定

提交按钮已设置type="submit",表单的onSubmit会触发handleAdd,无需再绑定onClick={handleAdd}:

<Button type="submit" color="primary">
  Submit
</Button>

补充:修复依赖缺失

代码中未显示useState的导入,需从react中导入,否则会引发报错:

import { useState } from 'react';

完整修复后的核心代码片段

import { useState } from 'react';
import { addDoc, collection} from "@firebase/firestore";
import { db, auth } from '../../services/authService';
import { useNavigate } from 'react-router-dom';

function MyModal({ isOpen, onClose }) {
    const [postText, setPostText] = useState("");
    const [feeling, setFeeling] = useState("")

    const postsCollectionRef = collection(db, "posts");
    const navigate = useNavigate();

    const handleFeelingClick = (value) => {
      setFeeling(value);
    };

    const handleAdd = async () => {
      try {
        await addDoc(postsCollectionRef, {
          feeling,
          postText,
          date: new Date().toISOString(),
          author: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
        });
        alert("publicación subida");
        navigate("/home");
      } catch (error) {
        alert(error.message);
      }
    };

    return (
        <Container>
            <Box component="form" onSubmit={handleAdd}>
                <Dialog open={isOpen} onClose={onClose}>
                    <DialogTitle>How are you feeling today?</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            <Button value="Good" onClick={() => handleFeelingClick("Good")}>
                                <CardMedia
                                    component="img"
                                    height="50"
                                    image={Good}
                                    alt="Feeling awesome"
                                />
                            </Button>
                            <Button value="Neutral" onClick={() => handleFeelingClick("Neutral")}>
                                <CardMedia
                                    component="img"
                                    height="50"
                                    image={Neutral}
                                    alt="Feeling Neutral"
                                />
                            </Button>
                            <Button value="Bad" onClick={() => handleFeelingClick("Bad")}>
                                <CardMedia
                                    component="img"
                                    height="50"
                                    image={Bad}
                                    alt="Feeling Bad"
                                />
                            </Button>
                        </DialogContentText>
                    </DialogContent>
                    {/* 以下原有内容保持不变 */}
                    <DialogContentText>
                        <DialogTitle>Type how are you feeling today...</DialogTitle>
                    </DialogContentText>
                    <Box
                        sx={{
                            marginLeft: '20px',
                            width: 300,
                            maxWidth: '100%',
                        }}
                    >
                        <TextField
                            fullWidth label="Type here your answer"
                            id="fullWidth"
                            onChange={(event) => {
                                setPostText(event.target.value);
                            }}
                            style={{
                                marginBottom: "10%"
                            
                            }} />
                    </Box>

                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <Box
                            sx={{
                                marginLeft: '20px',
                                width: 300,
                                maxWidth: '100%',
                            }}
                        >
                        </Box>
                        
                    </LocalizationProvider>
                    <DialogActions>
                        <Button onClick={onClose} color="secondary">
                            Close
                        </Button>
                        <Button type="submit" color="primary">
                            Submit
                        </Button>
                    </DialogActions>
                </Dialog>
            </Box>
        </Container>
    );
}

export default MyModal

内容的提问来源于stack exchange,提问作者Ricardo Sánchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:54:58