Fai*_*hid 2 prop reactjs react-native react-hooks
我正在使用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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的孩子组件如下:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我的控制台显示以下结果:
2:14:12 AM: Before Mount: null
2:14:12 AM: Mounted: null
2:14:12 AM: Mounted: 34.7821
Run Code Online (Sandbox Code Playgroud)
现在componentWillMount()在我的原始代码中有一个对Web服务的API调用,该调用依赖于this.state.latitude尚未传递的值,至少在第一次渲染时是这样.在第二次渲染时,当this.state.latitude值变为可用时,只render()执行该函数,但我需要在我的componentWillMount()函数中使用此值.
我在这里做错了什么?
Fai*_*hid 10
我无法接收道具值,componentWillMount因为此方法仅在初始渲染之前执行一次.由于在第一次渲染时没有将props从父组件传递给子组件,因此我通过componentWillReceiveProps在子组件中使用方法来解决问题.它在后续渲染时接收道具并更新我的子组件中的原始状态.这使我能够访问我的州值.我用来解决的代码如下:
componentWillReceiveProps(nextProps) {
// update original states
this.setState({
latitude: nextProps.latitude,
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16542 次 |
| 最近记录: |