React Native-如何在类组件中初始化对象?

时间:2018-12-18 21:25:40

标签: javascript react-native

当我尝试在类组件中初始化一个对象时,出现了此错误消息。

错误消息

    Failed to load bundle(http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false) with error:(SyntaxError: /blockchain/node_modules/react-native/App.js: Unexpected token (9:6)

我的代码

App.js

import Block from './block.js'

export default class App extends Component {

  let genesisBlock = new Block(); //error here
  let blockchain = new Blockchain(genesisBlock);

  render() {
    return (
      </View>

    );
  }
}

block.js

export default class Block {
    constructor() {
        this.index = 0
        this.previousHash = ""
        this.hash = ""
        this.nonce = 0
        this.transactions = []
     }

     addTransaction(transaction) {
        this.transactions.push(transaction)
    }

    get key() {
        return JSON.stringify(this.transactions) + this.index + this.previousHash + this.nonce
    }
}

但是如果我删除let,它说的是variable genesisBlock not found

参考:https://github.com/datomnurdin/blockchain-reactnative

2 个答案:

答案 0 :(得分:2)

尝试:

import Block from './block.js'

export default class App extends Component {
  constructor(){
    super()
    this.genesisBlock = new Block();
    this.blockchain = new Blockchain(this.genesisBlock);
  }

  render() {
    return (
      <View/>
    );
  }
}

答案 1 :(得分:0)

您的渲染具有关闭的View标记,没有打开的标记。