reactjs - react native : Passing props between components and componentWillMount() method

标签 reactjs react-native react-hooks prop

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

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

我在这里做错了什么?

最佳答案

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

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

关于reactjs - react native : Passing props between components and componentWillMount() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43313158/

相关文章:

javascript - 在 React 中通过 ID 访问 DOM 元素

reactjs - Lodash debounce 不会像预期的那样阻止调度 onChange

react-native - React Native 与 Android Pay(android) 和 Apple Pay(iOS) 集成

javascript - 如何监听 "ref"对象变化?

reactjs - 从kafka获取数据并发送到RSocket

javascript - 使用 Jest 模拟 Firebase onValue 函数

react-native - 如何绕过从透明重叠 View 到底层 View 的触摸事件

react-native - 如何使用 detox 处理纯原生元素

reactjs - 一般来说,在单个组件中使用一个或多个 useEffect 钩子(Hook)更好吗?

javascript - 在滚动事件上监听的函数中未更新 React Hook