繁体   English   中英

如何重新加载组件 ("<comment /> ) 在 reactjs 中?

[英]How to reload a component (" <Comment />) in reactjs?

我正在研究反应项目。 当我们单击 Post Comment 按钮时,我试图重新加载组件( <Comment /> )。 我实现了 onSubmit function,如下所示。 但它正在重新加载整个 window。 我只想重新加载那个“”组件,而不是整个 window。 谁能帮我解决这个问题? 我不明白该怎么做,请帮助......!

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import ImageHelper from "../helper/ImageHelper";
import { getoneBlog, postBlogComment } from "../helper/coreapicalls";
import { useHistory } from "react-router-dom";
import { isAutheticated } from "../../auth/helper/index";
import cogoToast from "cogo-toast";
import "../../styles.css";
import Comment from "./Comment";
import ShareButton from "react-web-share-button";

const Fullblog = (config) => {
  const useremail = isAutheticated() && isAutheticated().user.email;
  const blogId = useParams();
  const id = blogId._Id;
  // console.log(id);
  const history = useHistory();

  const [blog, setBlog] = useState({
    title: "",
    description: "",
    tags: "",
    photo: "",
    comment: "",
    loading: false,
    error: "",
    createdBlog: "",
    getaRedirect: false,
  });
  const [value, setvalue] = useState({
    user: useremail,
    content: "",
    err: "",
    success: false,
  });
  const [error, seterror] = useState(false);
  const [loading, setLoading] = useState(false);
  const { user, content, err, success } = value;

  const onInputChange = (name) => (event) => {
    setvalue({ ...value, err: false, [name]: event.target.value });
  };

  const onSubmit = (event) => {
    event.preventDefault();
    setvalue({ ...value, err: false });
    postBlogComment(id, { user, content })
      .then((data) => {
        if (data.error) {
          setvalue({ ...value, err: data.error, success: false });
        } else {
          setvalue({
            ...value,
            user: useremail,
            content: "",
            err: "",
            success: true,
          });
         
        }
      })
      .catch(console.log("Error in sending Comment"));
  };

  const loadBlog = () => {
    getoneBlog(id).then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setBlog(data);
        // console.log(data);
      }
    });
    setLoading(true);
  };

  useEffect(() => {
    loadBlog();
  }, []);
  ///////////////////////////// Post Submit Event ///////////////////

  const successMessage = () => {
    return (
      <div className="">
        <div className="">
          <div
            className="alert alert-success"
            style={{ display: success ? "" : "none" }}
          >
            Comment Posted..!
          </div>
        </div>
      </div>
    );
  };

  const errorMessage = () => {
    return (
      <div className="">
        <div className="">
          <div
            className="alert alert-danger"
            style={{ display: err ? "" : "none" }}
          >
            {err}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div>
      <div className="py-md-5 py-3">
        <div className="Fullblog container">
          <div>
            <h1 className="FullblogTittle">{blog.title}</h1>
            <p className="tags text-right">{blog.tags}</p>
            {loading ? (
              <ImageHelper blog={blog} />
            ) : (
              <div class="spinner-border text-danger" role="status"></div>
            )}
            <div
              className="description"
              dangerouslySetInnerHTML={{ __html: blog.description }}
            />
            <span>
              <ShareButton
                buttonStyle={{
                  color: "#ffca08",
                  background: "#fff",
                  padding: "10px 12px",
                  border: "none",
                  width: "100%",
                }}
              />
            </span>
            <div className="container Comment_stytum mt-4">
              {successMessage()}
              {errorMessage()}
              <div className="mx-sm-3 mb-2">
                <div className="">
                  <textarea
                    className="comment_input"
                    name="content"
                    value={content}
                    onChange={onInputChange("content")}
                    placeholder="Write Comment"
                  ></textarea>
                </div>
                <input
                  className="d-none"
                  name="user"
                  value={user}
                  onChange={onInputChange("user")}
                />
                <button type="submit" onClick={onSubmit} className="post-btn">
                  Post Comment
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <Comment />
    </div>
  );
};

export default Fullblog;

你能用这个修改来测试吗?

<form className="mx-sm-3 mb-2" onSubmot={onSubmit}>
  <div className="">
    <textarea
      className="comment_input"
      name="content"
      value={content}
      onChange={onInputChange("content")}
      placeholder="Write Comment"
    ></textarea>
  </div>
  <input
    className="d-none"
    name="user"
    value={user}
    onChange={onInputChange("user")}
  />
  <button type="submit" className="post-btn">
    Post Comment
  </button>
</form>

因为使用button type='submit'即将提交一个表单(但没有),通常使用submit ,我们在form上声明该方法。

要重新渲染组件,您应该更新他的 state 或道具,在您的情况下,我建议您尝试查找两个组件之间的关系,例如将评论数据作为道具发送,然后添加新评论后更新 state 和评论组件从 state 获取数据作为道具,因此它将自动重新渲染,否则,您可以使用 forceUpdate() 但我不建议这样做

https://reactjs.org/docs/react-component.html#forceupdate

暂无
暂无

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

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