[英]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.