Reactjs useState不支持第二次回调,有什么简单的解决方法?
这是我的Reactjs useState不支持第二次回调,有什么简单的解决方法?,reactjs,react-hooks,Reactjs,React Hooks,这是我的useffect useEffect(() => { let pageId = props.initialState.content[props.location.pathname.replace(/\/+?$/, "/")] .Id; if (props.initialState.currentContent.Url !== props.location. setCurrentContent({ currentConten
useffect
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
这样的方法,但是运气不好,我相信这是一个简单的解决方案,但我肯定错过了大局,提前谢谢你。你能做的就是编写一个效果,检查当前内容状态是否已更改且为空,并采取必要的措施。但是,您需要忽略初始渲染。另外,在类组件中,如果不将状态值作为对象传递,则只传递更新后的状态
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;
你想干什么?这里期望的结果是什么?由于某种原因,这不起作用,我看不到内容,从外观上看,它正在将内容设置为“”,但之后没有填充。@Andrew,似乎currentContent不是从useState返回的状态名称,相反,您必须在useEffect deps数组中添加state.currentContent。此为-ReferenceError:状态未定义,很抱歉打扰您,但我无法理解,可能必须将其设置回类组件。。。如果你想看的话,我已经让类组件工作了?@Andrew,这里的state只是一个例子。无论您如何调用由
useState
返回的状态,您都将使用该状态来代替状态
@Shaubham我已将currentContent作为状态,并且数据仍然不显示。。。不知道为什么,这是使用类组件的代码:然后这是不使用类组件的代码: