Nod*_*rat 2 reactjs react-hooks
locationHistory 在以下代码中始终为空数组:
export function LocationHistoryProvider({ history, children }) {
const [locationHistory, setLocationHistory] = useState([])
useEffect(() => history.listen((location, action) => {
console.log('old state:', locationHistory)
const newLocationHistory = locationHistory ? [...locationHistory, location.pathname] : [location.pathname]
setLocationHistory(newLocationHistory)
}), [history])
return <LocationHistoryContext.Provider value={locationHistory}>{children}</LocationHistoryContext.Provider>
}
Run Code Online (Sandbox Code Playgroud)
console.log总是记录[]。我试过在常规的 React 类中做完全相同的事情并且它工作正常,这让我认为我使用的钩子是错误的。
任何建议将不胜感激。
更新:删除useEffect( [history])的第二个参数可以修复它。但为什么?目的是不需要在每次重新渲染时重新运行此效果。因为它不应该需要。我认为这就是效果的工作方式。
添加一个空数组也会破坏它。它似乎[locationHistory]必须添加为第二个参数,useEffect以阻止它破坏(或根本没有第二个参数)。但我很困惑为什么这会阻止它破裂?history.listen应该在位置改变时运行。为什么useEffect每次locationHistory更改都需要重新运行,以避免上述问题?
PS 在这里玩一下:https : //codesandbox.io/s/react-router-ur4d3?fontsize =14(感谢 lissitz 在那里做了大部分工作)
您正在为history对象设置侦听器,对吗?
假设您的history对象在多次渲染中保持不变(完全相同的对象引用),这是您应该做的:
为此,您可以这样做:
useEffect(()=>{
history.listen(()=>{//DO WHATEVER});
return () => history.unsubscribe(); // PSEUDO CODE. YOU CAN RETURN A FUNCTION TO CANCEL YOUR LISTENER
},[]); // THIS EMPTY ARRAY MAKES SURE YOUR EFFECT WILL ONLY RUN AFTER 1ST RENDER
Run Code Online (Sandbox Code Playgroud)
但是如果你的history对象在每次渲染时都会改变,你需要:
useEffect(()=>{
history.listen(()=>{//DO SOMETHING});
return () => history.unsubscribe(); // PSEUDO CODE. IN THIS CASE, YOU SHOULD RETURN A FUNCTION TO CANCEL YOUR LISTENER
},[history]); // THIS ARRAY MAKES SURE YOUR EFFECT WILL RUN AFTER EVERY RENDER WITH A DIFFERENT `history` OBJECT
Run Code Online (Sandbox Code Playgroud)
注意:setState函数保证在每个渲染中都是相同的实例。所以它们不需要在依赖数组中。
但是如果你想访问你的useEffect. 你不应该像你那样直接使用它locationHistory(你可以,但如果你这样做,你需要将它添加到依赖数组,你的效果将在每次更改时运行)。为了避免直接访问它并将其添加到依赖数组中,您可以通过使用方法的函数形式来这样做setState。
setLocationHistory((prevState) => {
if (prevState.length > 0) {
// DO WHATEVER
}
return SOMETHING; // I.E.: SOMETHING WILL BE YOUR NEW STATE
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2196 次 |
| 最近记录: |