在React / React Native中获取道具的最佳方法是什么

时间:2019-11-15 23:18:25

标签: reactjs react-native

我真的在谈论React / React-Native中的道具。我有一个家长的看法。在此视图中,我从LocalStorage获取用户数据。['

import React, { Component } from 'react';
import { Container, Content, View } from 'native-base';
import NutrionalToolbar from '../../components/NutrionalToolbar';
import { AsyncStorage } from 'react-native';

export default class LogsScreen extends Component {

state = {
    user: '',
}

componentWillMount() {
    this._bootstrapAsync();
}

_bootstrapAsync = async () => {
    const user = await AsyncStorage.getItem('user');
    this.setState({ user: JSON.parse(user) })
};

render() {
    return (
        <Container>
            <NutrionalToolbar user={this.state.user} />
        </Container>
    );
}

}

现在在NutrionalToolbar组件中,我有了这个。

import React, { Component } from 'react';
import { View } from 'native-base';

class NutrionalToolbar extends Component {

constructor(props) {
    super(props)
    console.log(this.props) // This renders an empty user object
}



render() {
    console.log(this.props) // This renders the user object with values
    return (
        <View>
        </View>
    );
}
}

export default NutrionalToolbar;

如何在构造函数中获取this.props值。我在render方法中获取值。为什么不在构造函数内部工作?

1 个答案:

答案 0 :(得分:2)

我建议您研究componentDidUpdate生命周期挂钩,因为即使您可以访问user中的初始constructor道具,也无法访问该更新constructor中的道具。

import React, { Component } from 'react';
import { View } from 'native-base';

class NutrionalToolbar extends Component {

  componentDidUpdate() {
    console.log(this.props) // This will always log the current props
  }

  render() {
    return (<View></View>);
  }

}

export default NutrionalToolbar;