【问题标题】:react-router: 'history' is missing in type反应路由器:类型中缺少“历史”
【发布时间】:2019-03-03 00:24:21
【问题描述】:

App.tsx 的一些代码:

interface AppProps{
  history: any
}

export default class App extends React.Component<AppProps,...> {

  public state = {
    target: this.props.history.push('/')
  };

  private route() {
    if (!session.isLogin) {
        this.setState({ target: this.props.history.push('/') });
        return
    } else {
        this.setState({ target: this.props.history.push('/root') })
    }
  }
  ...
  public render() {
    return this.state.target
  }
}

index.tsx 的一些代码

ReactDOM.render(
  <MemoryRouter>
    <LocaleProvider locale={zhCn}>
        <App history={ ???? }/>
    </LocaleProvider>
  </MemoryRouter>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

为什么“历史”的类型不对?提示:类型“{}”中缺少属性“历史”。 index.tsx 应该传入哪些参数?

谢谢!

【问题讨论】:

  • 您确定您的界面正确吗?不应该是history?: any(可选)
  • 但是会提示“Cannot read property 'push' of undefined”

标签: reactjs typescript react-router-dom


【解决方案1】:

如果您希望App 接收来自MemoryRouter 的所有RouteComponentProps(包括历史对象),那么您需要通过路由调用App,如下所示:

ReactDOM.render(
  <MemoryRouter>
    <LocaleProvider locale={zhCn}>
        <Route component={App}/>
    </LocaleProvider>
  </MemoryRouter>,
  document.getElementById('root') as HTMLElement
);

那么你可以在App的声明中将AppProps替换为RouteComponentProps&lt;{}&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 2016-04-08
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2018-12-12
    • 2019-12-15
    • 2020-09-06
    相关资源
    最近更新 更多