我使用的是React Native 0.43。我有两个组件,分别命名为ParentComponent
和ChildComponent
。我想传递一些从父母到孩子的道具。我在父组件使用下面的代码(删节版):React Native:传递组件和componentWillMount()方法之间的道具
export default class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
latitude: 34.7821,
};
}
render() {
return (
<View>
<ChildComponent latitude={this.state.latitude} />
</View>
);
}
}
我的孩子组件如下:
export default class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
latitude: props.latitude,
};
}
componentWillMount() {
console.log('Before Mount: ' + this.state.latitude)
}
render() {
return (
<Text>{'Mounted: ' + console.log(this.state.latitude)}</Text>
);
}
}
现在,我的控制台显示以下结果:
2:14:12 AM: Before Mount: null
2:14:12 AM: Mounted: null
2:14:12 AM: Mounted: 34.7821
现在我的原始代码中的componentWillMount()
有一个API调用Web服务,这取决于this.state.latitude
的值,显然没有通过,至少在第一次呈现。在第二次渲染时,当this.state.latitude
值变为可用时,仅执行render()
函数,但在componentWillMount()
函数中需要此值。
我在做什么错在这里?
你可以在ComponentDidMount –