在本机反应中遇到变量(this.x)的问题

Having trouble with variables (this.x) in react native

我正在关注 this tutorial 以尝试让 tensorflow js 在 React Native 中工作。

教程的代码如下(有效,通过克隆 repo 测试):

class App extends React.Component {
  state = {
    isTfReady: false,
    isModelReady: false,
    predictions: null,
    image: null
  }

  async componentDidMount() {
    await tf.ready()
    this.setState({
      isTfReady: true
    })
    this.model = await mobilenet.load()
    this.setState({ isModelReady: true })
    this.getPermissionAsync()
  } 

而我的代码:

const modelJson = require('../assets/model/model.json');
const modelWeights = require('../assets/model/group1-shard1of1.bin');

class CameraCompo extends Component {
  async componentDidMount(){
    this.model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
  }

给我错误:属性 'model' 在类型 'CameraCompo'

上不存在

我尝试将 this.model 添加到构造函数中,如下所示:

  constructor(props){
    super(props)
    this.model = tf.GraphModel
  }

但是,它只是给了我同样的错误。

如有任何帮助,我们将不胜感激。

Typescript 抱怨 model 不是组件的 属性

可以为 props 和 typescript 的状态定义一个接口,以沿途推断它们。如果不是,可以将它们简单地设置为任何违背使用 typescript

目的的值
inferface Props {
 // add what is necessary
}

interface State {
   model: any
}

class CameraCompo extends Component<Props, State> {
  async componentDidMount(){

  const model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
  this.setState(model)
  // later model can be accessed with this.state.model.predict(input)
  }
}

以上就是定义一个模型,并将其设置在组件的状态中。但是模型几乎没有变化,可能不需要将其保持在组件状态。在这种情况下,只需声明模型

class CameraCompo extends Component {
      private model: any
      async componentDidMount(){
         this.model = await tf.loadGraphModel(bundleResourceIO(modelJson, modelWeights));
      }
}