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

时间:2020-05-26 03:49:12

标签: react-native tensorflow.js

我正在跟踪this tutorial来尝试使tensorflow js在react native中工作。

本教程的代码如下(正常运行,通过克隆存储库进行测试):

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'不存在属性'model'

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

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

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

Typescript抱怨model不是组件的属性

可以为道具定义一个接口,并为打字稿定义状态,以沿途推断道具。如果不是,则可以将它们简单地设置为不符合使用打字稿的目的

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));
      }
}