首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在本地模块回调上更改react-router-native位置

如何在本地模块回调上更改react-router-native位置
EN

Stack Overflow用户
提问于 2019-04-18 09:51:10
回答 1查看 566关注 0票数 0

我正在构建一个react原生应用程序,它显示Service overlay (就像那些facebook messenger气泡头),仅在Android中实现,在覆盖图上单击它应该会返回到特定屏幕中的应用程序。

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

App.js

代码语言:javascript
复制
<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

代码语言:javascript
复制
componentDidMount() {
    console.log(this.props.location.pathname);
    if(this.props.location.pathname === '/') {
        this.props.history.push("/home");
    }       
}

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

FloatingView.java

代码语言:javascript
复制
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中定义的,它还执行本机模块:

Search.js

代码语言:javascript
复制
<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 componentDidMount之前调用该函数,但不更新location.pathname。在它内部,函数是在调用之后调用的,但它不会导航到右侧屏幕。它总是落在/home中。

我认为这可能是一个生命周期问题,因为搜索组件没有挂载。我一直在想办法让这件事行得通。我尝试使用Redirect组件:

代码语言:javascript
复制
<Button onPress={() => FloatingView.init(() => <Redirect to="/progress" />)}

不管怎么说,有没有办法绕过这个问题呢?谢谢

EN

回答 1

Stack Overflow用户

发布于 2019-04-18 10:03:30

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

创建了一个单例navigation.js

navigation.js

代码语言:javascript
复制
export default {
    entryPoint: '/home'
};

并更改了以下文件:

Search.js

代码语言:javascript
复制
<Button onPress={() => FloatingView.init(() => {
   navigation.entryPoint = "/progress";
})}

Main.js

代码语言:javascript
复制
componentDidMount() {
    if(this.props.location.pathname === '/') {
        this.props.history.push(navigation.entryPoint);
    }       
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55738088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档