【问题标题】:React-Native-Navigation, how to refresh a route when navigating to it via navigation.navigate("routename", {randomparams})React-Native-Navigation,通过 navigation.navigate("routename", {randomparams}) 导航到它时如何刷新路由
【发布时间】:2020-06-01 15:34:49
【问题描述】:

我有一个bottomTabNavigator,它有两个stacknavigator。每个 stacknavigator 都有各自的屏幕。每当我使用类似

navigator.navigate("Stackname" {screen:"screenname", randomProp: "seomthing")

参数被发送到 stacknavigator,而不是屏幕本身。我通过传入有点解决了这个问题

initialParams=route.params

在堆栈导航器中,但是当我第二次调用第一个代码块时它们不会刷新。 有任何想法吗?

【问题讨论】:

    标签: javascript react-native react-native-navigation


    【解决方案1】:

    代替:

    navigator.navigate("StackName" {screen:"screenName", paramPropKey: "paramPropValue");
    

    使用这个:

    navigator.navigate("screenName", {'paramPropKey': 'paramPropValue'});
    

    在屏幕名称中:

    export default ({route}) => {
       useEffect(() => {
          // do something
       }, [route]);
    };
    

    【讨论】:

    • 这感觉很hacky,因为你发送的道具实际上并不重要,但它确实非常干净地强制每次导航重新渲染。
    【解决方案2】:

    那是因为屏幕已经安装并且初始参数不会更新。不过,您可以做的是创建一个使用“react-native-navigation”提供的“withNavigationFocus”增强的包装器组件。

    https://reactnavigation.org/docs/1.x/with-navigation-focus/

    ComponentWithFocus

    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”函数会找到与名称匹配的第一个可用屏幕,如果尚未安装,则将其安装到堆栈上(触发 componentDidMount 方法)。如果屏幕已经存在,它只是导航到它,忽略 'componentDidMount' 但传递 'isFocused' 道具,幸运的是,我们在 'ComponentWithFocus' 中挂钩。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 2020-06-25
      • 2022-06-15
      相关资源
      最近更新 更多