我正在构建一个反应本机应用程序,显示服务覆盖(如那些Facebook信使泡泡头),仅在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模块的回调被调用如下:
floating view.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
中定义,该组件也执行本机模块:
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
componentDidMount
之前调用,但location.pathname
未更新。在其中调用该函数,但它不会导航到右侧屏幕。它总是属于/home
。
我认为这是一个生命周期问题,因为未安装搜索组件。我一直试图想出办法让这项工作成功。我尝试使用Redirect
组件:
<Button onPress={() => FloatingView.init(() => <Redirect to="/progress" />)}
无论如何可以想到解决这个问题的方法吗?谢谢
找到了解决方案,不知道是不是最好的解决方案,但它确实有效。
创建了单身人士navigation.js
navigation.js
export default {
entryPoint: '/home'
};
并更改了以下文件:
Search.js
<Button onPress={() => FloatingView.init(() => {
navigation.entryPoint = "/progress";
})}
Main.js
componentDidMount() {
if(this.props.location.pathname === '/') {
this.props.history.push(navigation.entryPoint);
}
}