微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React、useEffect 清理不适用于 removeEventListener、useRef、视差效果

如何解决React、useEffect 清理不适用于 removeEventListener、useRef、视差效果

我正在尝试通过使用 useRef() 抓取 bubblesReftranslateY() onScroll 来将视差效果应用于 .svg 图像。

视差有效,但当我导航到下一页时,我收到错误TypeError: Cannot read property 'style' of null”。我认为这是因为导航到下一页addEventListener 仍在收听并尝试 useRef() 上的 bubblesRef。所以我在 useEffect()添加了清理功能,但这似乎并没有解决

感谢任何帮助。谢谢!

附言如果有人可以分享他们对像这样的简单视差效果方法,那也太棒了。这是我认为不会重新呈现页面 onScroll 上的所有其他内容的唯一方法

const HomePage = () => {
  const [loadedPosts,setLoadedPosts] = useState([]);
  const { sendRequest } = useHttpClient();
  console.log("loadedPosts homePage",loadedPosts);
  const bubblesRef = useRef();

  useEffect(() => {
    if (loadedPosts.length === 0) {
      //api call
    }
  },[sendRequest,loadedPosts]);

  useEffect(() => {
    const parallax = () => {
      let scrolledValue = window.scrollY / 3.5;
      bubblesRef.current.style.transform = `translateY(
      -${scrolledValue + "px"} 
      )`;
      console.log("scrolling...",scrolledValue);
    };
    window.addEventListener("scroll",parallax);
    return () => window.removeEventListener("scroll",parallax);
  },[]);

  return (

      <HomePageContainer>
        <Header />
        <SectionOne posts={loadedPosts} />
        <SectionTwo />
         <BubbleBlobs className="bubbleBlobs" ref={bubblesRef} />
        <BlobTop className="backBlobBottom" preserveAspectRatio="none" />
      </HomePageContainer>
   );
};

export default HomePage;

解决方法

每次向窗口添加侦听器时,您肯定都需要清理功能,否则处理程序(以及组件实例本身)将永远存在。然而,由于 React 异步运行这些清理钩子,它可能在其他窗口事件之后才会发生。组件卸载时ref的值设置为SELECT @rownum :=@rownum+1 as id,sc.id as b2_id,app.covid_id,app.payroll_batch,app.paid_by,app.date_receive,app.remarks,app.eligible,app.amount,app.amount_paid,app.amount_unpaid FROM `app_person` as app LEFT JOIN b2_sac_numbers AS sc ON sc.sac_number = app.covid_id ,因此在使用该值之前需要检查它是否仍然定义。

null
,

当您调用 import SwiftUI import Combine class AppState: ObservableObject { static let shared = AppState() @Published var project: String? //Just to mimic updates var count = 0 private init() { //Mimic getting updates to project Timer.scheduledTimer(withTimeInterval: 2,repeats: true){ timer in print("Timer") self.project = self.count.description self.count += 1 if self.count >= 15{ timer.invalidate() } } } } class MyViewModel: ObservableObject{ @Published var refreshedData: String = "init" let appState: AppState = AppState.shared var projectCancellable: AnyCancellable? init() { projectCancellable = appState.$project.sink(receiveValue: { value in print(value ?? "nil") self.refreshData() }) } func refreshData() { refreshedData = Int.random(in: 0...100).description } } struct MyView: View { @StateObject var vm: MyViewModel = MyViewModel() var body: some View { VStack{ Text(vm.refreshedData) } } } struct MyView_Previews: PreviewProvider { static var previews: some View { MyView() } } 时,您的引用尚未实例化,因此出现错误消息,在您的 useEffect 依赖项数组中,插入您的 ref 并在运行 useEffect 中的代码之前,确保定义了您当前的参考。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。