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

时间:2017-11-12 15:02:24

标签: javascript html reactjs

所以在我的React项目的html主管中,我有一些这样的脚本:

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

直接加载页面或刷新页面时工作正常,但是当我转换到另一个路径时,我需要再次运行这些脚本。由于不是整个页面被重新加载,只有某个组件,脚本不会重新运行而导致问题。

如何强制这些脚本再次运行?

1 个答案:

答案 0 :(得分: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);
相关问题