【问题标题】:Async redux dispatch causes memory leaks异步 redux 调度导致内存泄漏
【发布时间】:2020-07-29 21:19:37
【问题描述】:

当我在获取完成之前单击导航时,我面临以下警告。我该如何解决这个问题

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明内存泄漏 你的申请。要解决此问题,请取消 %s 中的所有订阅和异步任务。%s,一个 useEffect 清理函数

const SearchResultScreen = ({ navigation, route }) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedValue, setSelectedValue] = useState("lastHour");

  const dispatch = useDispatch();
  const newsies = useSelector((state) => state.searchResult.newsies);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      await dispatch(getSearchResults());
      setError(null);
    } catch (e) {
      setError("Something went wrong!");
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: () => (
        <TouchableWithoutFeedback onPress={() => navigation.replace("Search")}>
          <Text numberOfLines={1} style={styles.searchBtnText}>
            {route.params ? route.params.itemValue : ""}
          </Text>
        </TouchableWithoutFeedback>
      ),
      headerRight: () => (
        <HeaderButtons>
          <HeaderButton
            iconName="sliders"
            onPressed={() => {
              setModalVisible(true);
            }}
            style={{
              transform: [{ rotate: "-90deg" }],
              backgroundColor: "transparent",
            }}
          />
        </HeaderButtons>
      ),
    });
  }, [navigation, route]);

  if (loading) {
    return <CenteredSpinner />;
  }
  if (!loading && error) {
    return <CenteredErrorBox errorMsg={error} onPressed={fetchData} />;
  }
  if (!loading && newsies.length === 0) {
    return <CenteredErrorBox errorMsg={"No Data Found!"} />;
  }
  return (
    <>
      <CustomModal
        onClosed={() => setModalVisible(false)}
        modalVisible={modalVisible}
      >
        <Text style={styles.CustomModalTitle}>Search Filter</Text>
        <View style={styles.CustomModalBody}>
          <View style={styles.CustomModalBodyFilter}>
            <Text style={styles.CustomModalBodyFilterText}>Published at</Text>
            <CustomPicker
              items={[
                ["Last hour", "lastHour"],
                ["Last Day", "lastDay"],
                ["Last Week", "lastWeek"],
              ]}
              selectedValue={selectedValue}
              onValueChanged={(itemValue) => setSelectedValue(itemValue)}
            />
          </View>
        </View>
        <View style={styles.CustomModalActions}>
          <RippleButton
            style={{ marginRight: 10 }}
            onPressed={() => {
              setModalVisible(false);
            }}
          >
            <Text style={styles.CustomModalActionsBtn}>CANCEL</Text>
          </RippleButton>
          <RippleButton onPressed={() => {}}>
            <Text style={styles.CustomModalActionsBtn}>APPLY</Text>
          </RippleButton>
        </View>
      </CustomModal>
      <FlatList
        initialNumToRender={10}
        showsVerticalScrollIndicator={!Platform.OS === "android"}
        style={styles.list}
        renderItem={({ item }) => (
          <NewsBox
            news={item}
            onPressed={() => navigation.navigate("NewsDetail")}
          />
        )}
        data={newsies}
      />
    </>
  );
};

【问题讨论】:

    标签: reactjs react-native react-redux


    【解决方案1】:

    useEffect 钩子可能会返回在卸载组件时将调用一次以清理异步任务和订阅的函数。

    useEffect(()=>{
      // do some usefull staff here, for example subscribing or fetching data:
      ...
      // return cleaning function which will cancel subscribes and uncompleted fetches:
      return () => {
        ...
      }
    
    }, [])
    

    要取消 fetch 或任何其他异步操作,您可以尝试 AbortController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2015-07-06
      相关资源
      最近更新 更多