从导航道具设置初始状态 [英] Set initial state from navigation props

本文介绍了从导航道具设置初始状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Navigation 在屏幕之间进行路由.我有一个包含 FlatList 的初始屏幕,当我传递这样的参数时,单击我路由到新屏幕的项目.

I am using React Navigation to route between screen. I have an initial screen which contains a FlatList, onclick of an item I route to a new screen while passing params like this.

props.navigation.navigate('Details', {
    id: props.id,
    title: props.title
});

Details 屏幕中,我可以使用以下代码接收它,但是考虑到它是一个静态函数并且我无权访问 this.setState()<,我该如何设置状态/代码>.

In the Details screen I can receive it using the following code but how do I set the state considering it's a static function and I do not have access to this.setState().

static navigationOptions = ({navigation}) => {
    const {params} = navigation.state;

    console.log(params);
};

推荐答案

这将允许您在构造函数中处理它,这是以前放置在 componentWillMount 中的任何东西都可以去的其他位置.

This will allow you to handle it in the constructor, which is the other location anything that used to be placed in componentWillMount can go.

constructor(props) {
    super(props)
    this.state = {
        params: props.navigation.state.params
    }
}

作为参考,通过将 props 作为参数传递给构造函数,然后在其上运行 super 函数,您可以获得在调用任何其他生命周期函数之前设置初始状态或运行其他一次性函数的能力.

For reference, by passing in the props as an argument to constructor and then running the super function on them, you gain the ability to set your initial state or run other one-time functions before any other life-cycle functions are called.

这篇关于从导航道具设置初始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆