4

我正在使用 React Native 0.43。我有两个组件,名为ParentComponentChildComponent。我想将一些道具从父组件传递给子组件。我在父组件中使用以下代码(精简版):

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()函数中需要这个值。

我在这里做错了什么?

4

3 回答 3

10

我无法接收道具值,componentWillMount因为此方法仅在初始渲染之前执行一次。由于道具在第一次渲染时没有从父组件传递到子组件,因此我通过componentWillReceiveProps在子组件中使用方法解决了这个问题。它接收后续渲染的道具并更新我的子组件中的原始状态。这使我能够访问我的状态值。我用来解决的代码如下:

  componentWillReceiveProps(nextProps) {
      // update original states
      this.setState({
        latitude: nextProps.latitude,
      });
  }
于 2017-04-10T22:32:02.700 回答
4

你必须用“这个”这个词来称呼你的道具。

  constructor(props) {
    super(props);

    this.state = {
      latitude: this.props.latitude,
    };
  }

  componentWillMount() {
    console.log('Before Mount: ' + this.state.latitude)
  }
于 2017-04-10T00:40:04.690 回答
0

你得到道具里面

componentWillReceiveProps(nextProps) { // process your work }

于 2020-04-29T04:44:58.363 回答