React Native:在组件和 componentWillMount() 方法之间传递道具

React Native: Passing props between components and componentWillMount() method

我正在使用 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() 在我的原始代码中有一个 API 调用依赖于 this.state.latitude 的值的网络服务,这显然没有被传递,至少在第一个使成为。在第二次渲染时,当 this.state.latitude 值可用时,只有 render() 函数执行,但我的 componentWillMount() 函数中需要这个值。

我哪里做错了?

你必须用 "this" 术语调用你的道具。

  constructor(props) {
    super(props);

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

  componentWillMount() {
    console.log('Before Mount: ' + this.state.latitude)
  }

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

  componentWillReceiveProps(nextProps) {
      // update original states
      this.setState({
        latitude: nextProps.latitude,
      });
  }

你在里面得到道具

componentWillReceiveProps(nextProps) { // process your work }