首页 > 解决方案 > useState 不支持第二次回调,有什么简单的解决方法?

问题描述

这是我的useEffect

useEffect(() => {
    let pageId =
      props.initialState.content[props.location.pathname.replace(/\/+?$/, "/")]
        .Id;

    if (props.initialState.currentContent.Url !== props.location.
      setCurrentContent({ currentContent: { Name: "", Content: "" } }, () => {
        fetch(`/umbraco/surface/rendercontent/byid/${pageId}`, {
          credentials: "same-origin"
        })
          .then(response => {
            if (response.ok) {
              return response.json();
            }
            return Promise.reject(response);
          })
          .then(result => {
            setCurrentContent({
              currentContent: { Name: result.Name, Content: result.Content }
            });
          });
      });
    }
  }, []);

我已经尝试过useCallback/useMemo但没有运气,我确信这是一个简单的修复,但我必须错过更大的图景,在此先感谢。

标签: reactjsreact-hooks

解决方案


您可以做的是编写一个效果来检查 currentContent 状态是否已更改并为空并采取必要的操作。但是,您需要忽略初始渲染。同样在类组件中取消 setState 您不会将状态值作为对象传递,而只是传递更新的状态

const ContentPage = props => {
   const [currentContent, setCurrentContent] = useState({
    Name: props.initialState.currentContent.Name,
    Content: props.initialState.currentContent.Content
   });

  const initialRender = useRef(true);

   useEffect(() => {
     let pageId =
       props.initialState.content[props.location.pathname.replace(/\/+?$/, 
     "/")]
         .Id;
     if (
       initialRender.current &&
       currentContent.Name == "" &&
       currentContent.Content == ""
     ) {
       initialRender.current = false;
       fetch(`/umbraco/surface/rendercontent/byid/${pageId}`, {
         credentials: "same-origin"
       })
         .then(response => {
           if (response.ok) {
             return response.json();
           }
           return Promise.reject(response);
         })
         .then(result => {
           setCurrentContent({ Name: result.Name, Content: result.Content });
         });
     }
   }, [currentContent]);

   useEffect(() => {
     if (props.initialState.currentContent.Url !== props.location) {
       setCurrentContent({ Name: "", Content: "" });
     }
   }, []);
   ...
 };


 export default ContentPage;

推荐阅读