javascript - typescript - ReactRouter |箭头函数捕获 'this' 的全局值,隐含类型为 'any'

标签 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 错误?

最佳答案

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

对于传递状态的问题,您需要将其作为 prop 传递给 Routes 组件,该组件会将其分派(dispatch)到相关路径。

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>
)

关于javascript - typescript - ReactRouter |箭头函数捕获 'this' 的全局值,隐含类型为 'any',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185893/

相关文章:

javascript - React 在另一个对象中获取对象

javascript - 将值添加到具有基于数组的键深度的对象

typescript - typescript 在声明或转换/转换时是否有禁止 "any"的选项?

javascript - Angular - 使用可观察对象从静态 Web 服务中删除数据

typescript - 在 typescript 中 <T> 是什么意思?

javascript - 在javascript中添加滚动条

javascript - 如何将参数传递给 Vue @click 事件处理程序

javascript - Jquery 显示/隐藏 div - 修复重叠动画

javascript - 带扩展名的文件名验证

javascript - 促进将标签属性附加到数组内、对象内的每个对象的最佳/最有效方法是什么?