使用Mobx时在React App中路由错误

时间:2019-03-07 15:21:02

标签: reactjs mobx react-routing

当我将代码链接放入Mobx存储(const len)时,我立即得到一个React route错误。例如:

import React, { Component } from "react";
import { observer, inject } from 'mobx-react';

@inject('store') @observer class App extends Component {
  render() {
    const len = store.goods.length
    return (
      <div>
        <h1>App is there</h1>
        <fieldset>
          <legend>Done</legend>
          { len }
        </fieldset>
      </div>
    );
  }
}

如果我将其删除(store.goods.lenght),它将起作用,如果存在,则无法到达任何路线。它给我暴露了以下错误:

The above error occurred in the <App> component:
    in App (created by inject-App-with-store)
    in inject-App-with-store (created by Route)
    in Route (created by View)
    in Provider (created by View)
    in View
    in Router (created by BrowserRouter)
    in BrowserRouter

<Provider/>来自mobx。

更新

@withRouter声明之前添加装饰器App class之后,控制台中的该错误消失了。但这并不能解决问题,因为它现在无法显示路线,例如:

Cannot GET /notes

有人遇到过这种情况吗?

1 个答案:

答案 0 :(得分:1)

您能否张贴“发生以上错误[...]”部分的内容?但是我想,这可能是您正在访问存储而未在组件中声明它吗?在我看来,您应该像这样访问它:

@inject('store') @observer class App extends Component {
  render() {
    const len = this.props.store.goods.length
    return (
      <div>
        <h1>App is there</h1>
        <fieldset>
          <legend>Done</legend>
          { len }
        </fieldset>
      </div>
    );
  }
}

最好在其中添加一些null / undefined检查,除非您绝对保证商品是商店的一部分。