[英]React-Native-Navigation, how to refresh a route when navigating to it via navigation.navigate(“routename”, {randomparams})
我有一个bottomTabNavigator,它有两个stacknavigator。 每个 stacknavigator 都有各自的屏幕。 每当我使用类似的东西时
navigator.navigate("Stackname" {screen:"screenname", randomProp: "seomthing")
参数被发送到 stacknavigator,而不是屏幕本身。 我通过传入有点解决了这个问题
initialParams=route.params
在堆栈导航器中,但是当我第二次调用第一个代码块时它们不会刷新。 有任何想法吗?
那是因为屏幕已经安装并且初始参数不会更新。 但是,您可以做的是创建一个使用“react-native-navigation”提供的“withNavigationFocus”增强的包装器组件。
https://reactnavigation.org/docs/1.x/with-navigation-focus/
带焦点的组件
import React, {Component, useState} from 'react';
import { withNavigationFocus } from 'react-navigation';
const ComponentWithFocus = (props) => {
const {isFocused, onFocus, onBlur} = props;
const [focused, setFocused] = useState(false);
if(isFocused !== focused) {
if(isFocused) {
typeof onFocus === 'function' ? onFocus() : null;
setFocused(true)
} else {
typeof onBlur === 'function' ? onBlur() : null;
setFocused(false)
}
}
return (
props.children
)
}
export default withNavigationFocus(ComponentWithFocus);
并像这样在您的屏幕中使用它:
...
onFocus = () => {
//your param fetch here and data get/set
this.props.navigation.getParam('param')
//get
//set
}
...
render() {
<ComponentWithFocus onFocus={this.onFocus}>
/// Your regular view JSX
</ComponentWithFocus>
}
注意:如果参数仍然没有更新,那么您应该重新考虑您的导航方法。 例如,不需要像这样从 tabBar 导航:
navigator.navigate("Stackname" {screen:"screenname", randomProp: "seomthing")
您可以改为执行以下操作:
navigator.navigate("screenName", {'paramPropKey': 'paramPropValue'})
这将起作用,因为 '.navigate' function 找到与名称匹配的第一个可用屏幕,如果尚未安装,则将其安装到堆栈上(触发 componentDidMount 方法)。 如果屏幕已经存在,它只是导航到它,忽略“componentDidMount”但传递“isFocused”道具,幸运的是,我们在“ComponentWithFocus”中挂钩。
希望这可以帮助。
代替:
navigator.navigate("StackName" {screen:"screenName", paramPropKey: "paramPropValue");
用这个:
navigator.navigate("screenName", {'paramPropKey': 'paramPropValue'});
在屏幕名称中:
export default ({route}) => {
useEffect(() => {
// do something
}, [route]);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.