TypeScript - ReactRouter | 箭头函数捕获 'this' 的全局值,该值隐式具有类型 'any'

Jon*_*a33 7 javascript typescript reactjs react-router

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

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

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

Run Code Online (Sandbox Code Playgroud)

TS 说:

The containing arrow function captures the global value of 'this' which implicitly has type 'any' 在此处输入图片说明

最终目标是能够将 传递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>
      )
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能应用正确的类型来抑制这个 TypeScript 错误?

小智 7

箭头函数没有词法上下文,因此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>
)
Run Code Online (Sandbox Code Playgroud)