如何使用Prop的数据调用SetState?反应天然



我有一个组件之屋,在用户进入后。该屏幕中有一些数据,在标题中,我有一个图标按钮,该按钮将用户发送给用户的屏幕,其中用户可以看到他们的个人资料数据并删除帐户。因此,当单击"图标"按钮时,我将使用props.navigation发送数据,将用户发送到另一个屏幕/组件。

profile = () => {
        const { navigation } = this.props;
        const user = navigation.getParam('user', 'erro');
        this.props.navigation.navigate('profileScreen', { user: user });
    }

在新组件中,我尝试使用该数据在方法componentDidMount内进行设置,但它不起作用。我使用console.log检查了数据。在这种情况下,我该如何设定?

export default class profileScreen extends Component {
    static navigationOptions = {
        title: "Profile"
    };
constructor(props) {
    super(props);
    this.state = {
        user: {}
    }
}
componentDidMount() {
    const {navigation} = this.props;
    const user = navigation.getParam('user', 'Erro2');
    this.setState({user: user.user});
    console.log(this.state); // Object {"user": Object {},}
    console.log("const user");
    console.log(user.user); //my actual data is printed
}
render() {
    return (
        <Text>{this.state.use.name}</Text>
        <Text>{this.state.use.age}</Text>
        <Text>{this.state.use.email}</Text>
        ...
        ...
    )
}

}

console.log(this.state(

结果
Object {
  "user": Object {},
}

console.log(用户(

结果
Object {
  "createdAt": "2019-04-27T21:21:36.000Z",
  "email": "sd@sd",
  "type": "Admin",
  "updatedAt": "2019-04-27T21:21:36.000Z",
  ...
  ...
}

似乎您正在尝试将对象(user(作为带有React-Navigation库的路由参数。这是不可能的。

进行此类方案的正确方法是将用户的ID userId作为路由参数发送,并从API(或状态(加载用户详细信息。

profile = () => {
        const user = {id: 10 /*, ... rest of properties */}; // or take it from your state / api
        this.props.navigation.navigate('profileScreen', { userId: user.id });
    }

componentDidMount() {
    const {navigation} = this.props;
    const userId = navigation.getParam('userId', 'Erro2');
    // const user = read user details from state / api by providing her id
    this.setState({user: user});
}

ps:如果您使用的是状态管理(例如redux/flux/...(,请考虑在您的全球状态下设置currentUser,并将其读取而不是将用户ID作为路由参数。

确保在用户在状态渲染方法中获得新值时的组件更新应该是这样:

render() {
    const {user} = this.state
    return (
      <View>
        {user && <Text>{user.name}</Text>}
        {user && <Text>{user.age}</Text>}
        {user && <Text>{user.email}</Text>}
        ...
        ...
     </View>
    )
}

注意0:const {user} = this.state会使您免于重复this.state

注意1:将所有这些<Text>组件包装在另一个<View>中,以防止重复条件短语{user && ...}

更优雅

最新更新