通过反应导航传递状态

时间:2020-07-14 00:59:46

标签: react-native react-navigation

更新

好的,所以我走得更远。我使它工作了,但它很丑且有问题:)

我想做什么-我正在尝试在两个屏幕之间共享搜索字段。实际上,它与Yelp的工作方式几乎相同。第一个屏幕是地图,搜索字段位于顶部。当您单击搜索字段时,它将移至第二个搜索屏幕,在其中键入搜索词或选择某些默认搜索类别。

我有一个具有底部标签导航器(TS)的博览会应用。让我只粘贴重要部分:

export default function BottomTabNavigator() {
  return (
    <BottomTab.Navigator initialRouteName="Search">
      <BottomTab.Screen
        name="Search"
        component={SearchNavigator}
        ...

然后

const SearchStack = createStackNavigator<SearchParamList>();

function SearchNavigator() {
  return (
    <SearchStack.Navigator headerMode="none">
      <SearchStack.Screen name="SearchScreen" component={SearchScreen} />
      <SearchStack.Screen name="SearchFocusScreen" component={SearchFocusScreen} />
    </SearchStack.Navigator>
  );
}

SearchScreen

  const [searchQuery, setSearchQuery] = useState('');

  // If we returned from the second search screen with a search term, set it in state.
  useEffect(() => {
    if (route.params) {
      setSearchQuery(route.params.searchTerm);
    }
  }, [route]);

  const searchRef = useRef(null);
  const onFocus = () => {
    // If we have a search term, pass it to screen 2, then blur the input so we don't loop back.
    if (route.params) {
      setSearchQuery(route.params.searchTerm);
      navigation.navigate('SearchFocusScreen', { searchTerm: searchQuery });
    } else {
      navigation.navigate('SearchFocusScreen');
    }
    searchRef.current.blur();
  };

  return (
    <View>
      <MapView ... />
      <View>
        <SafeAreaView>
          <Searchbar
            ref={searchRef}
            placeholder="Search"
            value={searchQuery}
            onSubmitEditing={() => {
              initSearch({ searchQuery, region });
            }}
            onFocus={onFocus}
          />

第二个搜索屏幕

  const [searchQuery, setSearchQuery] = useState('');

  const searchRef = useRef(null);
  useEffect(() => {
    searchRef.current.focus();
    if (route.params) {
      setSearchQuery(route.params.searchTerm);
    }
  }, [route]);

  return (
    <SafeAreaView>
      <View>
        <Searchbar
          ref={searchRef}
          placeholder="Search"
          onChangeText={(query) => setSearchQuery(query)}
          value={searchQuery}
          onSubmitEditing={() => {
            navigation.navigate('SearchScreen', { searchTerm: searchQuery }); // Pass the search query back to Search page 1
          }}
          ...

可以吗?是。但这感觉不对。另外-还有一个问题,当我在搜索屏幕2的搜索字段中输入错误时,会得到自动更正的建议。如果我随后快速单击“搜索”,它会在之后自动纠正输入错误,并将错误发送到搜索屏幕1。并且可以看到。

如果你们有更好的策略来实现这一目标,请分享。

1 个答案:

答案 0 :(得分:0)

因为navigate是一个对象,所以useEffect仅比较参考值。如果您想更改该对象以触发useEffect,我将查看https://github.com/kentcdodds/use-deep-compare-effect