问题描述
我正在尝试通过使用 useRef()
抓取 bubblesRef
和 translateY()
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
中的代码之前,确保定义了您当前的参考。