简体   繁体   English

反应:默认 state 未在 useContext 中设置为道具

[英]React: Default state not being set as props in useContext

Hoping someone can help me here, I am trying to render a list of objects based on data coming from my useContext hook.希望有人可以在这里帮助我,我正在尝试根据来自我的 useContext 挂钩的数据呈现对象列表。 but the initial state using useState is being set to an empty array when trying to set it to a value from useContext, There are 6 objects in the projects data coming in, however I initially only want to render 4: and so am splitting the objects when they are received:但是使用useState的初始state在尝试将其设置为useContext中的值时被设置为空数组,项目数据中有6个对象进入,但我最初只想渲染4个:所以正在拆分对象收到时:

const LIMIT = 4

const { projects } = useContext(PortfolioContext); - this gets set fine - 这设置得很好

const [list, setList] = useState(projects.slice(0, LIMIT)); - list is an empty array - 列表是一个空数组

This is the map function that returns my elements:这是返回我的元素的 map function:

{list.map((project) => {... })} -- list is an empty array on first render {list.map((project) => {... })} -- list 在第一次渲染时是一个空数组

I have a function which allows me to render the other 2 objects when a button is clicked, this also works fine but shows only those 2 instead of adding to 4 that should already be displayed:我有一个 function 允许我在单击按钮时渲染其他 2 个对象,这也可以正常工作,但只显示那些 2 而不是添加到应该已经显示的 4:

`const loadMoreProjects = () => {
        const newIndex = index + LIMIT;
        const newShowMore = newIndex < projects.length - 1;
        const newList = concat(list, projects.slice(index, newIndex));
        setIndex(newIndex);
        setList(newList);
        setMoreProjects(newShowMore);
      };`

Here is a link to the file in full: https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/components/Projects/Projects.jsx这是完整文件的链接: https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/components/Projects/Projects.jsx

Here is a link to the data source: https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/mock/data.js这是数据源的链接: https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/mock/data.js

Here is a demo (you can see under 'Projects' nothing shows up): https://frosty-yalow-d8b34e.netlify.app/这是一个演示(您可以在“项目”下看到没有显示): https://frosty-yalow-d8b34e.netlify.app/

Thanks in advance: :)提前致谢: :)

I ended up just splitting my data to have a 'moreProjectsData' array with the rest of the objects and rendered that in a new component that displays when 'see more projects' is clicked:我最终只是将我的数据拆分为具有对象的 rest 的“moreProjectsData”数组,并将其呈现在单击“查看更多项目”时显示的新组件中:

https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/components/Projects/MoreProjects.jsx https://github.com/RossoMaguire/react-portfolio-website/blob/master/src/components/Projects/MoreProjects.jsx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM