redux 添加注解而不刷新页面:useEffect用作功能组件中的componentDidUpdate

cotxawn7  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个评论区,当我写评论时,它会存储在React-Redux中。我希望一旦写了评论,它会自动显示在评论区,但它不工作。相反,我需要改变页面视图(不刷新),例如返回主页,然后再回来,看到添加的评论。
不知何故,每次我向Redux reducer发送一个调度时,我都需要运行useEffect,这就是为什么useEffect具有
[dispatch]参数。但它不起作用。
我尝试过不带参数的useEffect,它导致了一个循环,这使得代码可以工作,因为注解被一次又一次地加载,但这是一个错误的举动。最终他们会禁止我使用我使用的数据库。

useEffect(() => {
    const loadComments = async (itineraryIdToCheck) => {
      await dispatch(commentsByItineraryId(itineraryIdToCheck));
    };
    loadComments(props.itineraryId);
  },  );

有人熟悉如何在这种情况下使用React钩子useEffect吗?提前感谢!
聊天:x1c 0d1x
注解组件

function Comments(props) {

    const[newTextState, setState] = useState([])

    //Here I download fro the first time the comments. 
    const commentsData = useSelector((state) => state.comments.allComments);
    const authenticatedUser = useSelector((state) => state.members.user);

    const dispatch = useDispatch();

  //componentDidUpdate. This should load all comments once you have written one, that is 
  //once a dispatch has been used. 

    useEffect(() => {
      const loadComments = async (itineraryIdToCheck) => {
        await dispatch(commentsByItineraryId(itineraryIdToCheck));
      };
      loadComments(props.itineraryId);
    }, [dispatch]);

    //here is where I obtained the input data from the form, and create a new comment that is submit-button-comments
    //to react redux
    async function newComment(event) {
      event.preventDefault();

      const commentObject = {
        itineraryId: props.itineraryId,
        text: [newTextState],
        memberId: authenticatedUser._id,
        profilePicture: authenticatedUser.profilePicture,
        userName: authenticatedUser.userName,
        city: props.city,
      };
        turnos += 1;
      console.log("comentario objecto", commentObject)
     dispatch(commentsPostByItinerary(commentObject))

    }
    //here is the list of comments

    let mappingComments =
      commentsData &&
      commentsData
        .filter((x) => x.itineraryId === props.itineraryId)
        .map((y) => {
          return (
            <div class="d-flex flex-row p-3">
              <img
                src={y.profilePicture}
                width="40"
                height="40"
                class="rounded-circle mr-3"
              />
              <div class="w-100">
                <div class="d-flex justify-content-between align-items-center">
                  <div class="d-flex flex-row align-items-center">
                    <span class="mr-2">{y.userName}</span>
                  </div>{" "}
                  <small>{date.fromNow} </small>
                  <small>
                    Date: y.timestamp</small>
                </div>
                <p class="text-justify comment-text mb-0">{y.text}</p>
              </div>
            </div>
          );
        });

    return (
      <div class="container mt-5 mb-5">
        <div class="row height d-flex justify-content-center align-items-center">
          <div class="col-md-7">
            <div class="card">
              <div class="p-3">
                <h6>Comments</h6>
              </div>

              <div class="mt-3 d-flex flex-row align-items-center p-3 form-color">

                <img
                  src={authenticatedUser.profilePicture}
                  width="50"
                  class="rounded-circle mr-2"
                />
                  <form onSubmit={(e) => newComment(e)}>
                  <div class="d-flex justify-content-center">
                    <input id="input-comments"
                        type="text"
                        class="form-control"
                        placeholder="Enter your comment..."
                        onChange={(e) =>
                          setState(e.target.value)}
                      />   
                         <button id="submit-button-comments" type="submit">                
                          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-send" viewBox="0 0 16 16">
                            <path d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576 6.636 10.07Zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z"/>
                          </svg>
                        </button> 
                        </div>
                  </form>

              </div>

              <div class="mt-2">{mappingComments}</div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  export { Comments };
aamkag61

aamkag611#

如果我没记错的话,redux保证了dispatch在重新呈现组件时不会被改变。因此,你的useEffect不会因为它而被再次触发。换句话说,你的useEffect只被调用一次,当这个组件第一次被使用/呈现的时候(想象一下它被useCallback或Memo嵌套)。
然而,实际上您应该将dispatch声明为useEffect依赖项。
我想你可以试试这样的东西(不优雅,但我认为它会起作用):


**let commentWasSubmmited = false;**

useEffect(() => {

**commentWasSubmmited = false;**

  const loadComments = async (itineraryIdToCheck) => {
    await dispatch(commentsByItineraryId(itineraryIdToCheck));
  };
  loadComments(props.itineraryId);

}, [dispatch,**commentWasSubmmited**]);

在这个例子中,我们使用了一个异步函数newComment(event){ event.


**commentWasSubmmited = true;**

......)
我也是一个React学生,如果我给你错误的信息,很抱歉。

相关问题