I'm using React Native 0.43. I've two components, named ParentComponent
and ChildComponent
. I want to pass some props from parent to child component. I'm using following code (abridged version) in parent component:
export default class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
latitude: 34.7821,
};
}
render() {
return (
<View>
<ChildComponent latitude={this.state.latitude} />
</View>
);
}
}
My child component is as following:
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>
);
}
}
Now, my console shows following result:
2:14:12 AM: Before Mount: null
2:14:12 AM: Mounted: null
2:14:12 AM: Mounted: 34.7821
Now componentWillMount()
in my original code has an API call to a web service which depends on the value of this.state.latitude
which clearly is not been passed, at least on the first render. On second render, when this.state.latitude
value become available, only the render()
function executes, but i need this value in my componentWillMount()
function.
What I'm doing wrong here?
答案 0 :(得分:7)
我无法在componentWillMount
中收到道具值,因为此方法仅在初始渲染之前执行一次。由于在第一次渲染时没有将props从父组件传递给子组件,因此我在子组件中使用componentWillReceiveProps
方法解决了该问题。它在后续渲染时接收道具并更新我的子组件中的原始状态。这使我能够访问我的州值。我用来解决的代码如下:
componentWillReceiveProps(nextProps) {
// update original states
this.setState({
latitude: nextProps.latitude,
});
}
答案 1 :(得分:3)
You have to call with "this" term your props.
constructor(props) {
super(props);
this.state = {
latitude: this.props.latitude,
};
}
componentWillMount() {
console.log('Before Mount: ' + this.state.latitude)
}
答案 2 :(得分:0)
您在里面有道具
componentWillReceiveProps(nextProps) {
// process your work
}