【发布时间】:2019-10-07 14:50:20
【问题描述】:
我正在使用一些具有动画效果的 jQuery 脚本..
由于它具有动画效果,每当在页面上呈现某些内容时,它必须一次又一次地工作,因此也应该刷新 jQuery 脚本。但问题是jQuery脚本没有刷新。
这是我的路由器:
export default () => (
<div>
<Menu />
<Switch>
<Route
exact path="/"
render={({ staticContext, match }) => {
const site = staticContext
? staticContext.site
: location.hostname.split(".")[0]
return <UniversalComponent site={site} match={match} page="core/Home" />
}}
/>
...
如您所见,我在 Switch 之外有一个 <Menu /> 组件。这就是加载 jQuery 脚本的地方。
class Menu extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
isDataFetched: false
};
this.loadExternalScripts = this.loadExternalScripts.bind(this);
}
componentDidMount() {
this._isMounted = true;
this.loadExternalScripts().then(() => {
if (this._isMounted) {
this.setState({ isDataFetched: true });
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
async loadExternalScripts() {
const postscribe = require('postscribe');
await postscribe('#react-root', '<script src="/vendor/js/jquery-3.3.1.min.js"></script>');
await postscribe('#react-root', '<script src="/vendor/bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>');
await postscribe('#react-root', '<script src="https://use.fontawesome.com/releases/v5.9.0/js/all.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/jquery.waypoints.min.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/waypoints.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/lightbox.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/owl.carousel.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/jquery.counterup.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/validator.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/contact.js"></script>');
await postscribe('#react-root', '<script src="/vendor/js/custom.js"></script>');
}
...
使用“postscribe”库,我加载了所有需要的 jQuery 脚本。
其中,脚本相关的导航切换按钮,效果很好,因为导航切换的东西与刷新与否无关。
但是,与动画相关的脚本,在任何页面加载时都应该刷新,它们只工作第一次,然后就不再工作了。因为jQuery只能在菜单组件第一次加载的时候加载。
当反应路由器为移动页面进行更改时,Menu 类中的componentDidMount() 似乎没有被触发(我猜如果触发它将刷新 jQuery)。这是我认为的问题,但不确定。
我该如何解决这个问题?
【问题讨论】:
-
您的脚本似乎被缓存了。只需向每个 URL 添加唯一(时间戳)查询以防止缓存。
标签: javascript jquery reactjs react-router