反应缓存不适用于Suspense。
我的代码
import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import { unstable_createResource as createResource } from "react-cache";
const MarkdownCache = createResource(input => {
return new Promise(resolve => resolve(input));
});
const App = () => {
return (
<Suspense fallback={<div>Loading...</div>}>
<Test />
</Suspense>
);
}
const Test = () => {
const input = MarkdownCache.read("Test react cache");
return input;
}
const rootElement = document.getElementById(“ root”); ReactDOM.render(,rootElement);
我使用的版本:
react: 16.8.0-alpha.0
react-dom: 16.8.0-alpha.0
react-cache: 2.0.0-alpha.1
答案 0 :(得分:1)
react-cache@2.0.0-alpha.1
的当前Alpha与新发布的react@16.8.0-alpha.0
和react-dom@16.8.0-alpha.0
不兼容。
降级到react@16.7.0-alpha.1
和react-dom@16.7.0-alpha.1
,直到发布新的兼容react-cache
的Alpha版本为止。
答案 1 :(得分:1)
修改/替换“ react-cache / cjs / react-cache.development.js”中的代码
OLD-:
var currentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
function readContext(Context, observedBits) {
var dispatcher = currentOwner.currentDispatcher;
if (dispatcher === null) {
throw new Error('react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.');
}
return dispatcher.readContext(Context, observedBits);
}
新-:
const ReactCurrentDispatcher =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
.ReactCurrentDispatcher;
function readContext(Context, observedBits) {
const dispatcher = ReactCurrentDispatcher.current;
if (dispatcher === null) {
throw new Error(
'react-cache: read and preload may only be called from within a ' +
"component's render. They are not supported in event handlers or " +
'lifecycle methods.',
);
}
return dispatcher.readContext(Context, observedBits);
}
答案 2 :(得分:0)
我从互联网上发现的此问题的解决方法是...
如果只想在开发环境中运行程序,则可以自己修改“ react-cache / cjs / react-cache.development.js”中的代码: 旧的:
var currentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
function readContext(Context, observedBits) {
var dispatcher = currentOwner.currentDispatcher;
if (dispatcher === null) {
throw new Error('react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.');
}
return dispatcher.readContext(Context, observedBits);
}
'currentOwner'除了在函数readContext中没有用。所以这是新的:
var currentDispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;
function readContext(Context, observedBits) {
var dispatcher = currentDispatcher.current;
if (dispatcher === null) {
throw new Error('react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.');
}
return dispatcher.readContext(Context, observedBits);
}
这在我的代码中有效。