我想将用户重定向到"/myblogs"页,当他们提交编辑后的帖子.useNavigate挂钩用于重定向.我收到的不是重定向,而是以下错误. 当我手动查看我的博客页面时,我可以看到更新的帖子.我不知道为什么会发生这个错误

const handleSubmit = e => {
  e.preventDefault();
  console.log(inputs);
  sendRequest().then(data =>
    console.log(data).then(() => navigate('/myBlogs/'))
  );
};

我的控制台中出现错误

BlogDetail.jsx:51 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')

以下是我的完整代码

const BlogDetail = () => {
  const navigate = useNavigate();
  const [blog, setBlog] = useState();
  const id = useParams().id;
  console.log(id);
  const [inputs, setInputs] = useState({});

  const { title, descritpion, imageURL } = inputs;

  const handleChange = e => {
    setInputs(inputs => ({
      ...inputs,
      [e.target.name]: e.target.value,
    }));
  };

  const fetchDetails = async () => {
    const res = await axios
      .get(`http://localhost:5000/api/blog/${id}`)
      .catch(err => console.log(err));
    const data = res.data;
    return data;
  };

  useEffect(() => {
    fetchDetails().then(data => {
      setBlog(data.blog);
      setInputs({
        title: data.blog.title,
        descritpion: data.blog.description,
        imageURL: data.blog.image,
      });
    });
  }, [id]);

  const sendRequest = async () => {
    const res = await axios
      .put(`http://localhost:5000/api/blog/update/${id}`, {
        title: inputs.title,
        descritpion: inputs.description,
      })
      .catch(err => console.log(err));
    const data = await res.data;
    return data;
  };

  console.log(blog);
  const handleSubmit = e => {
    e.preventDefault();
    console.log(inputs);
    sendRequest().then(data =>
      console.log(data).then(() => navigate('/myBlogs/'))
    );
  };

推荐答案

console.log是一个空的Return(i.e. returns 101),它不返回任何要从中链接的Promise对象.只需在LOG语句之后发出命令性导航.

const handleSubmit = e => {
  e.preventDefault();
  console.log(inputs);
  sendRequest()
    .then(data =>
      console.log(data);
      navigate('/myBlogs/');
    );
};

Javascript相关问答推荐

当promise 在拒绝处理程序被锁定之前被拒绝时,为什么我们会得到未捕获的错误?

Promise Chain中的第二个useState不更新

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

如何在模块层面提供服务?

如何从隐藏/显示中删除其中一个点击?

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

为什么这个.add.group({})在教程中运行得很好,但在我的游戏中就不行了?

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

删除元素属性或样式属性的首选方法

无法重定向到Next.js中的动态URL

react -原生向量-图标笔划宽度

如何根据输入数量正确显示alert ?

如果我的列有条件,我如何呈现图标?

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?

通过解构/功能组件接收props-prop验证中缺少错误"

Chrome上的印度时区名S有问题吗?

AstroJS混合模式服务器终结点返回404

使用Java脚本替换字符串中的小文本格式hashtag

通过ng-绑定-html使用插入的HTML中的函数