【发布时间】:2017-09-04 21:45:14
【问题描述】:
我正在使用 React Native 0.43。我有两个组件,分别名为 ParentComponent 和 ChildComponent。我想将一些道具从父组件传递给子组件。我在父组件中使用以下代码(精简版):
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() 有一个对Web 服务的API 调用,该调用取决于this.state.latitude 的值,显然没有传递,至少在第一次渲染时是这样。在第二次渲染时,当this.state.latitude 值可用时,只有render() 函数会执行,但我的componentWillMount() 函数中需要这个值。
我在这里做错了什么?
【问题讨论】:
-
可以在ComponentDidMount中处理
标签: reactjs react-native react-hooks prop