React Native:传递组件和componentWillMount()方法之间的道具
我使用的是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()
函数中需要此值。
我在做什么错在这里?
我没能在componentWillMount
获得道具的价值,因为这种方法只执行一次,只是初始渲染之前。由于道具没有在第一次渲染时从父组件传递到子组件,我通过在子组件中使用componentWillReceiveProps
方法来解决问题。它接收后续渲染的道具并更新我的子组件中的原始状态。这使我能够访问我的状态值。我用来解决的代码如下:
componentWillReceiveProps(nextProps) {
// update original states
this.setState({
latitude: nextProps.latitude,
});
}
你必须用“this”这个词来称呼你的道具。
中处理它不,不是。状态值用我的给定代码在第二次渲染迭代上打印。 –
你可以在ComponentDidMount –