【问题标题】:How to change react-router-native location on native-module callback如何在本机模块回调中更改 react-router-native 位置
【发布时间】:2019-04-18 01:51:10
【问题描述】:

我正在构建一个 react-native 应用程序,它显示服务覆盖(如那些 facebook messenger 泡泡头),仅在 Android 中实现,并且在覆盖上单击它应该返回到特定屏幕中的应用程序。

我正在使用 react-router-native,我的路由结构如下:

App.js

<NativeRouter>
    <ApolloProvider client={client}>
        <Main>
            <Switch>
                <Route exact path="/home" component={Home} />
                <Route exact path="/progress" component={RouteProgress} />
                <Route exact path="/search" component={Search} />
            </Switch>            
        </Main>
    </ApolloProvider>
</NativeRouter>

Main 组件有这些:

Main.js

componentDidMount() {
    console.log(this.props.location.pathname);
    if(this.props.location.pathname === '/') {
        this.props.history.push("/home");
    }       
}

我的 Native 模块的回调是这样调用的:

FloatingView.java

case MotionEvent.ACTION_UP:
        if (lastAction == MotionEvent.ACTION_DOWN || delta < 3) {
            Intent intent = new Intent(FloatingWindow.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

            FloatingViewPackage.callback.invoke();                                              

            stopSelf();
        }

回调定义在组件Search中,同样执行原生模块:

搜索.js

<Button onPress={() => FloatingView.init(() => {
    console.log('go to progress 1');
    this.props.history.push("/progress");

    setTimeout(() => {
        console.log('go to progress 2');
        this.props.history.push("/progress");
    }, 1000);
})}

问题是this.props.history.push("/progress"); 在超时之外和内部都不起作用。 在超时之外,函数在MaincomponentDidMount之前被调用,但location.pathname没有更新。在其中调用该函数,但它不会导航到正确的屏幕。它总是落入/home

我认为这是一个生命周期问题,因为未安装 Search 组件。我一直在想办法解决这个问题。我尝试使用Redirect 组件:

<Button onPress={() => FloatingView.init(() => <Redirect to="/progress" />)}

有没有办法解决这个问题?谢谢

【问题讨论】:

    标签: react-native react-native-android history react-lifecycle react-router-native


    【解决方案1】:

    找到了一个解决方案,不知道是不是最好的,但它确实有效。

    创建了一个单例navigation.js

    导航.js

    export default {
        entryPoint: '/home'
    };
    

    并更改了以下文件:

    搜索.js

    <Button onPress={() => FloatingView.init(() => {
       navigation.entryPoint = "/progress";
    })}
    

    Main.js

    componentDidMount() {
        if(this.props.location.pathname === '/') {
            this.props.history.push(navigation.entryPoint);
        }       
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多