繁体   English   中英

刷新站点后 UseEffect 停止工作

[英]UseEffect stop working after refreshing the site

我在 ReactJS 工作。 我有一个应该是另一种形式的配置的形式。 这种特定的形式看起来像这样:

  const [startingDate, setStartingDate] = useState();
  const [endingDate, setEndingDate] = useState();
  const [startingTime, setStartingTime] = useState();
  const [endingTime, setEndingTime] = useState();
  const [places, setPlaces] = useState();

  const createConfig = () => {
    Axios.post("http://localhost:3005/adminConfig", {
      startingDate,
      endingDate,
      startingTime,
      endingTime,
      places,
      organization: user._id,
    }).then((response) => {
      alert("successful")
    })
  }

在您将该数据发送到服务器后,我应该通过以下方式检索并将其设置为另一个表单的配置(第二个表单应该由其他人共享和填写):

const [config, setConfig] = useState([]);

  useEffect(() => {
    Axios.get(`http://localhost:3005/adminConfig/`).then((response) => {
      setConfig(response.data);
    });
  }, []);

          <input
            type="date"
            placeholder="Date of the meeting
            name="date"
            id="datePickerId"
            min={config[0].startingDate}
            max={config[0].endingDate}
            onChange={(event) => {
              setDate(event.target.value);
            }}
            required
          />

当您访问此表单并且尚未在 React 中设置配置时,它运行良好。 访问它并开始配置后,您可以看到它是如何更新的; 日期有限,理论上一切正常,当您刷新站点或其他人尝试访问时,问题就出现了,它停止工作,您必须删除设置(config[0].startingDate 等)

控制台显示:

无法读取未定义的属性(读取“startingDate”)

任何帮助表示赞赏

useEffect挂钩在页面加载后执行。 并且在初始页面加载时,未定义config[0]

一起使用可选链接和默认值:

<input
    type="date"
    placeholder="Date of the meeting"
    name="date"
    id="datePickerId"
    min={config[0]?.startingDate || 0} // <==  
    max={config[0]?.endingDate || 0} // <==
    onChange={(event) => {
        setDate(event.target.value);
    }}
    required
/>

如果可能,您可以使用后备值:

min={ config?.length > 0 ? config[0].startingDate : '1980-01-17'}

由于某些人没有管理员配置而出现错误的原因是可以的:

Axios.get(`http://localhost:3005/adminConfig/`).then((response) => 
{
  setConfig(response.data); 
});

尝试使 axios 请求也async ,这样它就不会返回空数组。

您可以使用可选链接来实现所需的行为,可选链接运算符 (?.) 使您能够读取位于连接对象链深处的属性的值,而无需检查链中的每个引用是否有效。

<input
        type="date"
        placeholder="Date of the meeting
        name="date"
        id="datePickerId"
        min={config[0]?.startingDate} //change this
        max={config[0]?.endingDate} //change this
        onChange={(event) => {
          setDate(event.target.value);
        }}
        required
      />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM