usecontext的有条件渲染
该任务要求我根据目标类别组从 API 获取数据。
例如,www.localhost:8000/women 会获取女性对应的所有数据,www.localhost:8000/women 会获取男性对应的所有数据。
我现在创建了一个通用的 ContextProvider,其中根据值获取数据。
为了更清楚起见,请查找下面的代码。
export const ProductCategoryContext = createContext();
const ProductCategoryContextProvider = ({ children }) => {
const [products, setProducts] = useState([]);
//conditional value which must be updated in onClick function of a <Link>.
const [targetGroup, setTargetGroup] = useState("");
const URL = `${process.env.REACT_APP_HOST}`;
async function getproducts() {
console.log(targetGroup);
console.log(123);
try {
if (targetGroup === "women") {
const womensData = await fetch(`${URL}/women`);
const jsonData = await womensData.json();
console.log(jsonData?.items);
setProducts(jsonData?.items);
} else if (targetGroup === "men") {
console.log(targetGroup);
const mensData = await fetch(`${URL}/men`);
const jsonData = await mensData.json();
console.log(jsonData?.items);
setProducts(jsonData?.items);
}
} catch (error) {
console.error(error);
}
}
useEffect(() => {
getproducts();
}, []);
return (
<ProductCategoryContext.Provider
value={{
product: products,
targetGroup: targetGroup,
setTargetGroup: setTargetGroup,
}}
>
{children}
</ProductCategoryContext.Provider>
);
};
事件处理程序的代码如下:
const { setTargetGroup } = useContext(ProductCategoryContext);
return (<Link
onClick={() => setTargetGroup("women")}
className="category-links"
to="/create/women"
>
<div className="card">
<div className="card_image">
<img
className="category-images"
src={require("../../assets/images/women-tile-image.jpg")}
alt="image for womens section"
/>
</div>
</div>
</Link>)
现在,targetGroup 的值仍未更新,因此我无法获取数据。我很困惑可能是什么问题?
The task requires me to fetch data from an API, based on target category groups.
For example, www.localhost:8000/women fetches all data corresponding to women, and www.localhost:8000/women fetch all data corresponding to men.
I have now created a common ContextProvider where data is fetched based on a value.
Please find the code below for better clarity.
export const ProductCategoryContext = createContext();
const ProductCategoryContextProvider = ({ children }) => {
const [products, setProducts] = useState([]);
//conditional value which must be updated in onClick function of a <Link>.
const [targetGroup, setTargetGroup] = useState("");
const URL = `${process.env.REACT_APP_HOST}`;
async function getproducts() {
console.log(targetGroup);
console.log(123);
try {
if (targetGroup === "women") {
const womensData = await fetch(`${URL}/women`);
const jsonData = await womensData.json();
console.log(jsonData?.items);
setProducts(jsonData?.items);
} else if (targetGroup === "men") {
console.log(targetGroup);
const mensData = await fetch(`${URL}/men`);
const jsonData = await mensData.json();
console.log(jsonData?.items);
setProducts(jsonData?.items);
}
} catch (error) {
console.error(error);
}
}
useEffect(() => {
getproducts();
}, []);
return (
<ProductCategoryContext.Provider
value={{
product: products,
targetGroup: targetGroup,
setTargetGroup: setTargetGroup,
}}
>
{children}
</ProductCategoryContext.Provider>
);
};
The code for the event handler is as below:
const { setTargetGroup } = useContext(ProductCategoryContext);
return (<Link
onClick={() => setTargetGroup("women")}
className="category-links"
to="/create/women"
>
<div className="card">
<div className="card_image">
<img
className="category-images"
src={require("../../assets/images/women-tile-image.jpg")}
alt="image for womens section"
/>
</div>
</div>
</Link>)
Now, the value of targetGroup remained unupdated because of which I am unable to fetch the data. I'm confused about what the problem could be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所见,
useEffect
钩子缺少对引用的targetGroup
状态值的依赖。空的依赖数组告诉 React 在初始渲染时运行一次效果。由于targetGroup
初始状态值为""
,因此不会提取任何内容,因此效果不会“侦听”任何依赖项更改为可能重新提取。将
targetGroup
添加到useEffect
挂钩的依赖项数组中,以便在更新时触发效果回调。将URL
和getproducts
移动到useEffect
回调正文中,以将它们作为依赖项删除。您可能还会发现为 React hook 添加 ESLint 插件 很有帮助。它将帮助您解决缺少依赖项和其他常见的 React hook 问题。
From what I can see, the
useEffect
hook is missing a dependency on the referencedtargetGroup
state value. The empty dependency array tells React to run the effect once on the initial render. Since thetargetGroup
initial state value is""
nothing is fetched and then the effect isn't "listening" for any dependency to change to possibly refetch.Add
targetGroup
to theuseEffect
hook's dependency array so when it updates the effect callback is triggered. MoveURL
andgetproducts
into theuseEffect
callback body to remove them as dependencies.You may also find adding the ESLint plugin for React hooks helpful. It will help you with missing dependencies and other general React hook issues.