打字稿-ReactRouter |箭头函数捕获隐式类型为“ any”的“ this”的全局值

时间:2019-01-14 16:54:47

标签: javascript reactjs typescript react-router

我正在使用render={() => </Component />}通过React Router 4渲染组件

我需要将状态传递给给定的组件,即:<Game />

export const Routes: React.SFC<{}> = () => (
  <Switch>
    <Route path="/" exact={true} component={Home} />
    <Route path="/play-game" render={() => <Game {...this.state} />} />
    <Redirect to="/" />
  </Switch>
)

TS中断说:

The containing arrow function captures the global value of 'this' which implicitly has type 'any' enter image description here

最终目标是能够将Routes传递到我的主应用程序:

export default class App extends Component<{}, AppState> {
  public state = {
    // state logic
  }

  public render(): JSX.Element {
      return (
        <BrowserRouter>
          <div className="App">
            <Navigation />
            <Routes />
          </div>
        </BrowserRouter>
      )
  }
}

如何应用正确的类型来抑制此TypeScript错误?

1 个答案:

答案 0 :(得分:2)

箭头函数没有词法上下文,因此在箭头主体内对this的任何调用都会在其外部范围内退化为它的值。这就是TS的抱怨。

对于传递状态的问题,您需要将其作为道具传递给Routes组件,然后将其分派到相关的路线。

export default class App extends Component<{}, AppState> {
  public state = {
    // state logic
  }

  public render(): JSX.Element {
      return (
        <BrowserRouter>
          <div className="App">
            <Navigation />
            <Routes state={this.state}/>
          </div>
        </BrowserRouter>
      )
  }
}

// you need to pass the correct type to React.SFC<>
// probably something along React.SFC<{ state: State }>
// where State is the type of `state` field in App.
export const Routes: React.SFC<...> = ({ state }) => (
  <Switch>
    <Route path="/" exact={true} component={Home} />
    <Route path="/play-game" render={() => <Game {...state} />} />
    <Redirect to="/" />
  </Switch>
)