reactjs - URL 更改时需要调用 useEffect 挂钩
问题描述
我试图让这个组件根据其当前的 url 加载数据,无论是 /global 还是 /my-posts。useEffect() 从组件的第一次加载中获取数据,但是当我更改为另一个 url 时,我希望 useEffect 再次检查 url 并加载正确的数据,但我却被第一次加载的数据卡住了。每次单击不同的 url(如 /global 和 /my-posts url)时,如何让 useEffect 调用。
export default function Dashboard() {
const [allRecipes, setAllRecipes] = useState([]);
const [myRecipes, setMyRecipes] = useState([]);
const currentUrl = window.location.pathname;
useEffect(() => {
if (currentUrl === '/dashboard/global') {
console.log('hello');
trackPromise(
RecipeService.getAllRecipes()
.then((data) => {
setAllRecipes(data);
}),
);
} else if (currentUrl === '/dashboard/my-posts') {
console.log('hi');
trackPromise(
RecipeService.getRecipes()
.then((data) => {
setMyRecipes(data);
}),
);
}
}, []);
console.log(window.location.pathname);
return (
<>
<div className="dashboard">
<DashboardHeader />
<div className="created-posts">
{allRecipes.length !== 0
? allRecipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
: null}
{myRecipes.length !== 0
? myRecipes.recipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
: null}
{currentUrl === '/dashboard/create' ? <CreateForm /> : null}
<LoadingIndicator />
</div>
</div>
</>
);
}
解决方案
要React.useEffect
在每次currentUrl
更改时运行,您必须将其添加到useEffect
依赖项数组中。
// first we need to control the state of window.location.pathname by react not the browser
// and make react state be the only source of truth.
const pathname = window.location.pathname
// manage currentUrl in state.
const [currentUrl, setCurrentUrl] = React.useState(pathname)
React.useEffect(() => {
setCurrentUrl(pathname)
}, [pathname])
// now you would add the contolled `currentUrl` state to its useEffect deps.
useEffect(() => {
if (currentUrl === '/dashboard/global') {
// ..........
} else if (currentUrl === '/dashboard/my-posts') {
// ..........
}
}, [currentUrl]);
推荐阅读
- ruby - 算法挑战数字格式问题
- flutter - 背景位置 - Flutter
- azure-resource-manager - ARM 模板全球化
- python - Flask Blueprint 扩展布局但找不到模板
- javascript - 在 JS 中显示课程和模块
- laravel - 即使凭据为真,具有两种不同模型的 Laravel 8 Multiple Auth 也会返回 False
- jmeter - 了解 Jmeters 线程组持续时间
- flutter-animation - 颤动动画显示列表项的移动
- javascript - 如何将 adobe leonardo 输出的对象数组转换为更简单的对象以进行顺风配置
- metal - Metal 得到一个断言,断言失败`sourceLevel(1) must be < [sourceTexture mipmapLevelCount](1)。(lldb)