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

Posted

技术标签:

【中文标题】如何在 reactjs 中重新加载组件(“<Comment />)?【英文标题】:How to reload a component (" <Comment />) in reactjs? 【发布时间】:2021-03-09 12:58:07 【问题描述】:

我正在研究 React 项目。当我们单击“发表评论”按钮时,我试图重新加载一个组件 (&lt;Comment /&gt;)。我实现了 onSubmit 函数,如下所示。但它正在重新加载整个窗口。我只想重新加载那个“”组件,而不是整个窗口。谁能帮我解决这个问题? 我不明白该怎么做,请帮助......!

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;

【问题讨论】:

【参考方案1】:

你能测试一下这个修改吗?

<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 上声明方法。

【讨论】:

不起作用 :( 我认为我的帖子评论按钮和 之间没有关系 谢谢,请回答这个问题 ***.com/q/66156615/15160538 @farvilain【参考方案2】:

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

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

【讨论】:

你能告诉我如何在 Post Comment 和 之间建立关系,我的 Comment 组件 ------------------- -------------------------------------------------- ---------------- > 从“react”导入反应, useEffect,useState;从“../helper/coreapicalls”导入 getBlogComments ;从“../../image/user.png”导入user_img;从“react-router-dom”导入 useParams ;导入“../../styles.css”; const Comment = () => const blogId = useParams();常量 id = blogId._Id; // console.log(id); const [showComment, setShowComment] = useState([]);常量 [错误,设置错误] = useState(false); const [加载,setLoading] = useState(false); useEffect(() => loadComments(); , []); const loadComments = () => getBlogComments(id).then((data) => if (data.error) seterror(data.error); else setShowComment(data.评论); // console.log(data.comment); );设置加载(真); ; return (showComment.map((comment, index) => return ( comment.user

comment.content

时间comment.createdAt
);));;跨度>

以上是关于如何在 reactjs 中重新加载组件(“<Comment />)?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ReactJS 中触发模型更改的重新渲染?

如何在不刷新页面的情况下在 ReactJS 中重新加载?

ReactJS:即使在重新渲染组件后复​​选框状态仍然存在

如何在状态更改(父)reactjs时重新渲染子组件

Reactjs:如何在组件内创建带有 args 的函数

如何在 ReactJS 中有条件地加载组件