我使用RESTool (https://github.com/dsternlicht/RESTool)作为API-UI,我需要在React渲染完所有内容之后运行js-script。window.onload和$(document).ready不起作用。
发布于 2020-10-04 21:41:06
我假设您使用的是react函数组件。对于渲染后发生的每个副作用,请使用useEffect-hook (如果您不知道,可以在文档中进行读取,您将经常需要它)。然后,您可以动态导入脚本并在钩子中使用它。在中,我包含了一个加载脚本的网络请求,以防您自己不能使用它。
function Component() {
useEffect(() => {
// This happens after rendering with a script requested from an API
makeAPIRequest.then((script) => script.doThisAndThat())
// This assumes you have your script locally, then you can import it dynamically to speed up initial render. Note that when dynamically importing you must default export the script
import('./myScriptThatShouldExecuteAfterRender').then((script) => script.doThis())
})
render(
<SomeThing />
)
}您也可以正常导入脚本,然后在useEffect中执行它。动态导入只是为了在您向用户呈现某些内容之后加载脚本,并改进用户体验。
https://stackoverflow.com/questions/64195206
复制相似问题