在 react native 中使用变量 (this.x) 时遇到问题



我正在按照本教程尝试让 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));
}

给我错误:类型"相机组合"上不存在属性"模型">

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

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

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

任何帮助将不胜感激。

Typescript 抱怨model不是组件的属性

可以为 props 定义一个接口,并为打字稿定义一个状态,以在此过程中推断它们。如果不是,可以简单地将它们设置为任何违背使用打字稿的目的

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

最新更新