无法在组件类中获取当前路由

时间:2016-06-09 13:52:42

标签: javascript reactjs ecmascript-6 redux react-router

我有一个中间件设置检查静态需求,基本上在呈现页面之前准备异步数据,我在尝试传递我的api调用函数getWaitingListPosition时遇到了一个问题。 :

export default class WaitingListPage extends React.Component {
  static need = [
    getWaitingListPosition(this.props.routeParams.token)
  ]

  ...
}

我收到错误cannot read props of undefined

这是使用react-router v2.4.1

从以下网址访问此组件的网址:https://mywebsite.com/w/:token

1 个答案:

答案 0 :(得分:1)

静态方法无权访问实例(this)属性。你应该这样做,它需要routeParams的prop,然后调用函数。

static need = (routeParams) => {
  // make sure to return a promise
  return getWaitingListPosition(routeParams.token)
}

<强>更新

这需要在渲染过程中调用......就像这样。

// assuming a promise, call the static method on the routed component
RoutedComponent.need(routeParams)
.then((data) => {
  render(<RoutedComponent data={data}/>)
}