首页 > 解决方案 > 如何在本机模块回调中更改 react-router-native 位置

问题描述

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

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

应用程序.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组件有这些:

主.js

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

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

浮动视图.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");在超时之外和内部都不起作用。在超时之外,该函数在之前被调用Main componentDidMountlocation.pathname没有更新。在其中调用该函数,但它不会导航到正确的屏幕。它总是落入/home.

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

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

无论如何可以想办法解决这个问题吗?谢谢

标签: react-nativereact-native-androidhistoryreact-lifecyclereact-router-native

解决方案


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

创建了一个单例navigation.js

导航.js

export default {
    entryPoint: '/home'
};

并更改了以下文件:

搜索.js

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

主.js

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

推荐阅读