我在componentDidMount()
中调用了以下库,它成功返回了一个对象。
componentDidMount() {
var objData =call.MyLibStart('12121', this);
}
现在我需要在objData
部分中使用render()
。我还需要访问objData
的某些属性,例如objData.
render() {
//I need the object.postate here
}
如何在那里访问对象?在这里使用国家是个好主意吗?
答案 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
函数之后运行。您的应用流程如下:
constructor()
:this.objData = null
{li} in render()
:this.objData = null
{li} in componentDidMount()
:this.objData = some object
醇>
此时渲染功能不会更新,因为只有在对状态进行了一些更改后才会更新。由于this.objData
不是状态,因此它在render
中始终为空。因此,通过将componentDidMount
更改为componentWillMount
,objData
在render
被调用时不会为空。
答案 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
}