【问题标题】:React Native: Passing props between components and componentWillMount() methodReact Native:在组件和 componentWillMount() 方法之间传递道具
【发布时间】:2017-09-04 21:45:14
【问题描述】:

我正在使用 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() 函数中需要这个值。

我在这里做错了什么?

【问题讨论】:

  • 可以在ComponentDidMount中处理

标签: reactjs react-native react-hooks prop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

      constructor(props) {
        super(props);
    
        this.state = {
          latitude: this.props.latitude,
        };
      }
    
      componentWillMount() {
        console.log('Before Mount: ' + this.state.latitude)
      }
    

    【讨论】:

    • 不,不是这样。使用我给定的代码在第二次渲染迭代时会打印状态值。
    【解决方案3】:

    你在里面得到道具

    componentWillReceiveProps(nextProps) { // process your work }

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2017-03-11
      • 2017-09-24
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多