React-Native-Navigation,如何通过navigation.navigate(“ routename”,{randomparams})

问题描述 投票:0回答:1

我有一个bottomTabNavigator,它具有两个stacknavigator。每个堆栈导航器中都有各自的屏幕。每当我使用类似

的东西时
navigator.navigate("Stackname" {screen:"screenname", randomProp: "seomthing")

参数被发送到堆栈导航器,而不是屏幕本身。我通过传递

就解决了这个问题
initialParams=route.params

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

javascript react-native react-native-navigation
1个回答
0
投票

这是因为屏幕已经安装并且初始参数不会更新。但是,您可以做的是创建一个包装容器组件,并通过“ 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”中。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.