reactjs - 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
但没有运气,我确信这是一个简单的修复,但我必须错过更大的图景,在此先感谢。
解决方案
您可以做的是编写一个效果来检查 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;
推荐阅读
- redirect - 使用参数将根“/”重定向到 uri
- excel - 设置过滤器范围
- .htaccess - .htaccess,将整个文件夹(在根目录上)重定向到子域
- c++ - 将 c++ cmake-library build 发布到本地 repo 时出现 Gradle 错误
- logging - 使用多个触发策略时限制日志文件的总数 Log4j2
- django - 用户创建视图的 API 测试用例失败
- android - ListView 在按钮单击时填充多次
- android - 在颤振单元测试中访问 rootBundle
- reactjs - UseEffect 挂钩的 Jest 测试用例
- python - vscode无法打开Python交互,出现如下错误