如何在React路由更改时重新运行脚本

3

因此,在我的 React 项目的 html head 中,我有一些脚本,像这样:

<head>
...
<script src="SomeJavaScript.js" type="text/javascript"></script>
...
</head>

当直接加载页面或刷新页面时,它可以正常工作,但是当我转到另一个路由时,我需要重新运行这些脚本。由于只重新加载了某个组件而不是整个页面,因此脚本不会重新运行,从而导致问题。
如何强制重新运行这些脚本?
1个回答

1
在脚本中:
<script>
  window.someMethod = function() {
    // do something here
  };

  window.someMethod();
</script>

在 React 中:
import { withRouter } from 'react-router'

/// ...

const someMethod = window.someMethod;

class App extends React.Component {

  static propTypes = {
    location: React.PropTypes.object.isRequired
  }

  // ...

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.onRouteChanged();
    }
  }

  onRouteChanged() {
    someMethod();
  }

  // ...
  render(){
    return <Switch>
        <Route path="/" exact component={HomePage} />
        // ...
        // ...
        <Route component={NotFound} />
      </Switch>
  }
}

export default withRouter(App);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接