react-native - 如何在本机模块回调中更改 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
componentDidMount
但location.pathname
没有更新。在其中调用该函数,但它不会导航到正确的屏幕。它总是落入/home
.
我认为这是我的生命周期问题,因为未安装 Search 组件。我一直在想办法解决这个问题。我尝试使用该Redirect
组件:
<Button onPress={() => FloatingView.init(() => <Redirect to="/progress" />)}
无论如何可以想办法解决这个问题吗?谢谢
解决方案
找到了一个解决方案,不知道是否最好,但它有效。
创建了一个单例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);
}
}
推荐阅读
- python - 如何计算列表中的选票并将其存储在字典中以跟踪选票数量
- java - 将 Predicate<> 转换为子类型
- javascript - 如何在定义后立即使用变量 - js
- pdf-generation - Sejda HTML to PDF:如何在显示表格的所有页面上保留标题?
- python - 如何在 AllenNLP 中加载微调的 sciBERT 模型?
- .net-core - 我应该在管道中的 WebAppDeployment 之前还是之后进行 2e2 测试?
- vue.js - Vue 3 组件 - 试图调用 AJAX
- php - 教义迁移不会识别注释的更改(在生产中)
- c# - 在遍历循环时将新对象添加到字典中?
- spring - Spring Boot:找不到位于带有@Value注释的资源文件夹中的文件