【发布时间】:2020-12-11 17:56:42
【问题描述】:
我试图让这个组件根据其当前 url 加载数据,无论是 /global 还是 /my-posts。 useEffect() 从组件的第一次加载中获取数据,但是当我更改为另一个 url 时,我希望 useEffect 再次检查 url 并加载正确的数据,但我却被第一次加载的数据卡住了。每次单击 /global 和 /my-posts url 等不同 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>
</>
);
}
【问题讨论】:
-
将 currentUrl 传递给 useEffect 依赖数组 => [currentUrl]
-
将
currentUrl添加到useEffect的dep 数组中。现在它没有接收到变化,因为你没有向它提供你想要观察的变量。
标签: reactjs react-hooks