带有reducer的搜索API的性能不佳

我搜索了我的本机应用程序。一切都按预期工作,但性能不佳。

这是我的搜索栏组件:

      <TextInput
        autoCapitalize='none'
        autoCorrect={false}
        style={styles.inputStyle}
        placeholder='Search'
        value={term}
        onChangeText={onTermChange}
        onEndEditing={onTermSubmit}
        returnKeyType='search'
      />
    </View>

这是我正在使用搜索栏组件的搜索屏幕

  const search = term => {
    fetchData(
      `URL?term=${term}`
    );
  };

        <SearchBar
          term={term}
          onTermChange={setTerm}
          onTermSubmit={() => {
            search(term);
          }}
        />

onTermSubmit should run only onEndEditing calling fetchDatawith the term.

fetchData is my reducer which looks like this:

const dataFetchReducer = (state, action) => {
  switch (action.type) {
    case "FETCH_INIT":
      return {
        isLoading: true
      };
    case "FETCH_SUCCESS":
      return { isLoading: false, data: action.payload.result.data };
    case "FETCH_FAILURE":
      return {
        isLoading: false,
        isError: true
      };

    default:
      return state;
  }
};

const fetchData = dispatch => {
  return async url => {
    dispatch({ type: "FETCH_INIT" });
    try {
      const result = await axios(url);
      dispatch({ type: "FETCH_SUCCESS", payload: { result } });
    } catch (error) {
      dispatch({ type: "FETCH_FAILURE" });
    }
  };
};

For the reducer I use useContext.

但是,当我控制台log(state.data)时,我注意到我在键入时会立即取回数据。我想这就是为什么我的表现不好。不过不知道为什么。我以为fetchData仅在用户按键盘上的“搜索”按钮时运行?

评论