【发布时间】:2019-11-21 23:26:28
【问题描述】:
我正在尝试通过将 refName.current.offsetTop 值保存到来自多个组件的上下文中来制作平滑的滚动条。
- Context 当前只设置了最后一个 setState。
- 我的代码如下所示,以避免添加我运行的 2 个组件 useEffect 中的多个 setSectionTops(设置上下文状态)。
组件
const ProjectsList = () => {
const {addSectionTop} = useContext(NavContext)
let projectsRef = useRef()
let ref2 = useRef()
let ref3 = useRef()
useEffect(()=>{
addSectionTop('projects', projectsRef.current.offsetTop)
addSectionTop('ref2', ref2.current.offsetTop)
addSectionTop('ref3', ref3.current.offsetTop)
},[])
return (
<section className="ProjectsList" id="ProjectsList" ref={projectsRef}>
{/* {console.log('ProjectList:', navRefs)} */}
<h2 ref={ref2}>Projects</h2>
<div ref={ref3}>
<Project />
</div>
</section>
)
}
上下文
export const NavContext = createContext()
const NavContextProvider = props => {
const [expanded, setExpanded] = useState(false)
const [sectionTops, setSectionTops] = useState({})
const toggleExpanded = () => {
setExpanded(!expanded)
}
const addSectionTop = (newNavStr, refOffsetTop) => {
// console.log('sectionTops:',sectionTops)
const newSectionTop = {[newNavStr]: refOffsetTop}
// console.log('newNavRef:',newNavRef)
setSectionTops({...sectionTops, ...newSectionTop})
console.log(sectionTops)
}
const scrollTo = refKey => {
const refOffSetTop = sectionTops[refKey]
window.scrollTo({ top: refOffSetTop, behavior: 'smooth' })
}
const value = {
expanded,
toggleExpanded,
sectionTops,
addSectionTop,
scrollTo
}
console.log(value)
return (
<NavContext.Provider value={value}>{props.children}</NavContext.Provider>
)
}
在这段代码的最后,sectionTops: 中的所有 I 都是 {ref3: 799}。
- 也许我不明白 useEffect 是如何工作的。从我如何拥有它 用 ,[] 写我在想它相当于 组件DidMount()。所以对我来说,它应该加载上下文 组件安装后的数据。
- 这可能是上下文中的生命周期问题 b/c 没有足够的时间来更新状态?
谢谢
【问题讨论】:
标签: reactjs react-hooks