react-native - 在本机反应中遇到变量(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
}
但是,它只是给了我同样的错误。
任何帮助将不胜感激。
解决方案
打字稿抱怨这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));
}
}
推荐阅读
- android - E/dalvikvm: JNI ERROR (app bug): local reference table overflow (max=512)
- python - 如何在python中获取数组中一批元素的索引?
- java - SQL 错误:1064,SQLState:42000 在@Query - JPA,MySQL,Hibernate
- javascript - 当我的音效启动时背景音乐变得失真
- visual-studio - “使用模式匹配”消息
- javascript - 未跨多个 useEffects 定义全局变量
- excel - 复制没有背景颜色的 Excel 范围
- android - Android Webview 文件和相机上传 - Kotlin
- javascript - Node-JS 链接未在邮件中打开
- octave - 如何修复在 Ubuntu 中使用 Intel MKL 产生错误结果的 Octave?