将参数从屏幕传递到Header组件反应导航

时间:2020-03-26 17:33:56

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

我的问题是我无法将函数作为参数传递给react-navigation v5中的标头组件。

从下面的filtersscreen.js中的给定代码中,我想将savefilters传递给navigation.js中的headerRight。

我可以在log-1中查看保存参数。但是,为什么我无法在log-2(FilterNavigator)中获取保存参数。

当我使用setParams()时收到警告-“导航状态中发现不可序列化的值,这可能会破坏诸如持久和恢复状态之类的用法。如果您传递了不可序列化的值,例如函数,类实例等。如果需要在选项中使用带有回调的组件,则可以使用'navigation.setOptions'。有关更多详细信息,请参见https://reactnavigation.org/docs/troubleshooting.html#i-get-the-warning-we-found-non-serializable-values-in-the-navigation-state。”

当我使用navigation.setOptions({save:savefilters})时,我在route.params.save中找不到保存文件

我是本机反应的新手,请您解决此问题。

我阅读了文档React Navigation v5

我在下面记录了输出。 谢谢。

navigation.js

const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        options={{
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => console.log(props)} //log-2 attached below
                />
              </TouchableNativeFeedback>
            </View>
          ),
        }}
        name="Filters Meals"
        component={FiltersScreen}
      />
    </screen.Navigator>
  );
};

FiltersScreen.js

const FilterSwitch = props => {
  return (
    <View style={styles.filterContainer}>
      <Text>{props.label}</Text>
      <Switch
        trackColor={{true: Colors.primaryColor}}
        thumbColor={Colors.primaryColor}
        value={props.state}
        onValueChange={props.onChange}
      />
    </View>
  );
};

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({
      save: saveFilters,
    });
    console.log('useEffect : ', props); //log-1 attached below
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};

log-1

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "pop": [Function anonymous
        ],
        "popToTop": [Function anonymous
        ],
        "push": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "replace": [Function anonymous
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters Meals-7XbV4LEyLo",
        "name": "Filters Meals",
        "params": {
            "save": [Function anonymous
            ]
        }
    }
}

log-2

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters-6CuzlMQv2w",
        "name": "Filters",
        "params": undefined,
        "state": {
            "index": 0,
            "key": "stack-7UXVGRjyv-",
            "routeNames": [Array
            ],
            "routes": [Array
            ],
            "stale": false,
            "type": "stack"
        }
    }
}

3 个答案:

答案 0 :(得分:1)

onPress={() => console.log(props)}

替换此

onPress={route.params?.save}

反应导航4倍,不再需要getParam

navigation.getParam('someParam', 'defaultValue');

等效于:

route.params?.someParam ?? 'defaultValue';

Documentation react navigation official

答案 1 :(得分:1)

在React-navigation v5中,您必须设置并获取这样的参数

//您的navigation.js应该是

    const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        name="Filters Meals"
        component={FiltersScreen}
        options={({route, navigation}) => ({
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => route.params.save()} 
                />
              </TouchableNativeFeedback>
            </View>
          ),

         })}

      />
    </screen.Navigator>
  );
};

//您的FiltersScreen组件应为

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({save: saveFilters});
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};

如果仍然有问题,可以参考此仓库 GitHub Repo

快乐编码;-)

答案 2 :(得分:0)

在FilterNavigator的第二行中,放入

const { save } = props.route.params;

再往下走

onPress = {save}