首页 > 解决方案 > 在本机反应中遇到变量(this.x)问题

问题描述

我正在按照本教程尝试让 tensorflow js 在本机反应中工作。

本教程的代码如下(工作,通过克隆 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));
  }

给我错误:“CameraCompo”类型上不存在属性“模型”

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

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

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

任何帮助将不胜感激。

标签: react-nativetensorflow.js

解决方案


打字稿抱怨这model不是组件的属性

可以为 props 和 state 定义一个接口,以便 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));
      }
}

推荐阅读