我用了一个技巧来解决这个问题,但要记住的是,它们仍然是不稳定的 API,反应使用并且仍然建议不要在生产级别使用 React 服务器组件,使用它来学习和测试它并获得你自己熟悉它,所以回到解决方案:
我的经验是,我在他们的 depo 应用程序中使用的缓存层遇到了很多问题。我刚刚删除了它。我的建议是在这些功能和 API 变得稳定之前暂时不要使用它。所以我在我的 useServerResponse(...) 函数中删除了它,在这里我将它重命名为 getServerResponse(...) 因为我后来为了将承诺转换为实际可渲染响应而创建的钩子,所以我所做的是:
export async function getServerResponse(location) {
const key = JSON.stringify(location);
// const cache = unstable_getCacheForType(createResponseCache);
// let response = cache.get(key);
// if (response) return response;
let response = await createFromFetch(
fetch("/react?location=" + encodeURIComponent(key))
);
// cache.set(key, response);
return response;
}
然后创建一个钩子,从上面的函数中获得承诺,并为我返回一个实际的可渲染结果:
export function _useServerResponse(appState) {
const [tree, setTree] = useState(null);
useEffect(() => {
getServerResponse(appState).then((res) => {
setTree(res);
});
}, [appState]);
return { tree };
}
最后在我的AppContextProvider 中,我使用该钩子获取 React 服务器组件树,并使用该渲染树作为我在客户端的全局上下文提供程序的子项,如下所示:
import { _useServerResponse } from ".../location/of/your/hook";
export default function AppContextProvider() {
const [appState, setAppState] = useState({
...someAppStateHere
});
const { tree } = _useServerResponse(appState);
return (
<AppContext.Provider value={{ appState, setAppState }}>
{tree}
</AppContext.Provider>
);
}
我知道这就像一个变通办法 hacky 解决方案,但它在我的情况下工作得很好,而且似乎直到我们获得稳定的 API 以及关于 RSC 的适当官方文档,它至少对我来说是一个可行的解决方案!