将更新的状态传递到反应导航屏幕

时间:2018-03-22 00:06:49

标签: react-native react-navigation

如何将新状态传递给React Navigation功能?

我的代码目前看起来像这样:

我父类的简化视图:

constructor(props){
    super(props)

    this.state = {
        code: "aaa"
    }

    this.refresh = this.refresh.bind(this)
}


refresh() {
    this.setState({
        code: "bbb"
    })
}

async componentDidMount(){
    const {navigate} = this.props.navigation

    navigate("Child", {screen: "Screen Two", code: this.state.code, refresh: this.refresh})

}

在子课程中,我会执行以下操作:

this.props.navigation.state.params.refresh()

我面临的问题:

选项1:如果我有当前的代码,它将不会将新的状态值传递给导航器,因为它不在渲染函数中

选项2:如果我将代码放在渲染函数中,它会向我发出警告:“在现有状态转换期间无法更新”。

我做错了什么,如何解决这个问题?

更多详情 我正在使用此主屏幕从Web上的API加载一些细节并将其存储在状态中。我希望能够将刷新功能传递给第二个屏幕,我可以使用它将API中的数据重新加载到主屏幕上。一旦数据加载回主屏幕上的状态,它应该传播回第二个屏幕。如果不使用导航器,这似乎很容易,但我不知道如何使用导航器。

由于学习曲线,我目前不想使用redux,但是希望将来某个时候能够使用redux。

1 个答案:

答案 0 :(得分:1)

所以你试图在你的子组件中调用refresh()方法。如果你使用这个内部渲染函数,将重复调用refresh()方法,它将发出警告:“在现有状态转换期间无法更新”。

如果保持代码不变,它将更新父类状态。但是,当您访问this.props.navigation.state.params.code时,不会反映该更新。这只会给出'aaa'的值。

选项1;

您可以使用redux并轻松处理此方案。

选项2;

如果你真的想知道父类状态的值,你可以将一个函数作为导航参数传递给子,这将返回状态的值。

家长班。

 constructor(props){
    super(props)

    this.state = {
        code: "aaa"
    }

    this.refresh = this.refresh.bind(this);
    this.getState = this.getState.bind(this)
 }

 refresh() {
     this.setState({ code: "bbb" })
 }

 getState() {
     return this.state.code;
 }

 async componentDidMount(){
     const {navigate} = this.props.navigation

     navigate("Child", {screen: "Screen Two", code: this.state.code, refresh: this.refresh, getState: this.getState })
 }

在您的子类中使用以下代码来获取父类状态。

 let parentClassState = this.props.navigation.state.params.getState();
相关问题