从componentDidMount()访问对象

时间:2017-11-07 15:11:55

标签: javascript react-native

我在componentDidMount()中调用了以下库,它成功返回了一个对象。

  componentDidMount() {
      var objData =call.MyLibStart('12121', this);
}

现在我需要在objData部分中使用render()。我还需要访问objData的某些属性,例如objData.

 render() {
//I need the object.postate here
}

如何在那里访问对象?在这里使用国家是个好主意吗?

3 个答案:

答案 0 :(得分:4)

您可以像@ 3Dos的答案一样访问该对象。如果要修改objData的值,请将其用作状态。如果您只想呈现该对象或获取值以检查某些内容,那么类属性就足够了。

确保以正确的方式获取对象:

componentWillMount () {
  this.objData = Object.assign({}, call.MyLibStart('12121', this))
  console.log('objData: ', this.objData) // inspect the object in debugger to check it's keys
}

componentDidMount的原因是它仅在render函数之后运行。您的应用流程如下:

    {li} in constructor()this.objData = null {li} in render()this.objData = null {li} in componentDidMount()this.objData = some object

    此时渲染功能不会更新,因为只有在对状态进行了一些更改后才会更新。由于this.objData不是状态,因此它在render中始终为空。因此,通过将componentDidMount更改为componentWillMountobjDatarender被调用时不会为空。

答案 1 :(得分:1)

你想要的可能是在构造函数中设置一个实例变量,这样你就可以在其他类方法中访问它,比如例如:

class MyComponent extends Component {
  constructor (props) {
    super(props)
    this.objData = call.MyLibStart('12121', this)
  }

  render () {
    // Do whatever you like with this.objData
    return null
  }
}

答案 2 :(得分:0)

除非您需要访问已安装的组件,否则可以在构造函数中将其设置为初始状态:

constructor(props) {
  super(props)
  this.state = {
    objData: call.MyLibStart('12121', this)
  }
}
render() {
  // use this.state.objData here
}