如何在React中初始化不同组件的数据

huangapple go评论68阅读模式
英文:

How to initialise data to different components in React

问题

我正在学习React,并尝试完成一些Frontmentor的高级项目。

我正在构建一个电影应用程序,其中包含不同的页面,如主页列出所有电影,电影页面仅列出电影,电视剧页面和书签页面。还提供了JSON数据。

JSON数据具有以下结构。

{
   "title": "Beyond Earth",
   "thumbnail": {
     "trending": {
       "small": "img",
       "large": "img"
     },
     "regular": {
       "small": "img",
       "medium": "img",
       "large": "img"
     }
   }
   "year": 2021,
   "category": "Movie",
   "rating": "PG",
   "isBookmarked": false,
   "isTrending": true
}

我的问题是:如何最好地管理这个JSON数据,因为它将在所有不同的页面上在它们的初始加载时被使用?

请记住,用户应该能够在点击按钮时更改isBookmarked状态。我应该使用RTK、context还是存储在远程数据库中并使用React Query进行管理?

我正在使用这些项目来学习不同的技术,但想了解每种情况下的最佳方法。

我的最初思路是使用Redux Toolkit,但后来了解到reducers应该是纯的。我还考虑过在Supabase中为数据创建一个数据库,但在如何创建具有这种数据结构的数据库方面遇到了问题。

我目前有一个本地存储钩子,可以将数据加载到本地存储中,并可以返回电影的值和setValue。但不知道如何使所有组件都能够使用它。

英文:

I am learning React and trying to complete some Frontmentor advance projects.

I am building a movie app with different pages like a home page that list all the movies, a movie page that list only the movies, a TV Series page and a bookmarked pages. Also a json data provided.

The json data has this kind of structure.

 {
    "title": "Beyond Earth",
    "thumbnail": {
      "trending": {
        "small": "img",
        "large": "img"
      },
      "regular": {
        "small": "img",
        "medium": "img",
        "large": "img"
      }
    }
    "year": 2021,
    "category": "Movie",
    "rating": "PG",
    "isBookmarked": false,
    "isTrending": true
  },

My question is: What is the best way to manage this json data, as it will be consumed by all the different pages on their initial load ?

Keep in mind that users should be able to change the isBookmarked status when a button is clicked. Should I used, RTK, or context or store in a remote db and manage with React query?

I am using these projects to learn different technologies but want to know the best for each situation.

My initial process was to use a redux toolkit, but later learnt that reducers should be pure. Also thought about creating a database for the data in supabase but ran into problem on how to create the db with this data structure.

I currently have a local storage hook that loads to that to local storage and can return the value and setValue for the movies. But don't know how that can be consumed by all components

答案1

得分: 0

可以做的一件事是创建一个上下文,该上下文可以用于轻松地将数据传递给所有组件。

上下文的创建方式如下:

const MoviesContext = createContext({});

export function MoviesProvider({ children }) {
  const [movies, setMovies] = useState([]);

  // 在这里放置获取电影的方法。它与在经典函数组件中执行相同

  // 我没有在你的 JSON 中看到任何 id,但最好使用 id 而不是索引
  const bookmark = (index) => {
    const clone = structuredClone(movies);
    clone[index].isBookmarked = !clone[index].isBookmarked;
    setMovies(clone);
  }

  return (
    <MoviesContext.Provider value={{ movies, bookmark }}>
      {children}
    </MoviesContext.Provider>
  )
}

然后,你可以用提供者包装父组件。使用上下文的每个组件应该作为 MoviesProvider 的子元素来调用。

<MoviesProvider>
  <Content />
</MoviesProvider>

请注意,如果你使用 react-router 并且所有页面都需要上下文,你可以将 &lt;Routes /&gt; 放置在 &lt;MoviesProvider /&gt; 的子元素中。

然后,在每个子组件中,你可以使用 useContext 钩子访问上下文:

const { movies, bookmark } = useContext(MoviesContext);

你还可以在上下文文件中创建一个快捷方式:

export const useMovies = () => useContext(MoviesContext);

这样你只需这样调用它:

const { movies, bookmark } = useMovies();

就是这样!

如果你想要从上面初始化一些值,也可以将属性传递给提供者。

在 React 中,上下文非常有用,如果你想了解更多,我建议阅读文档:

如果你有任何问题,或者我的回答不够详细,请随时提问。

英文:

One thing you can do is to create a context that can be used to easily pass the data to all the components

A context is created like this :

const MoviesContext = createContext({});

export function MoviesProvider({children}) {
  const [movies, setMovies] = useState([]);

  // Here you put your method to fetch the movies. It is just like
  // doing it in a classic functional component

  //  I didn&#39;t see any id in your json, but it is better to use 
  // id instead of index
  const bookmark = (index) =&gt; {
     const clone = structuredClone(movies)
     clone[index].isBookmarked = !clone[index].isBookmarked;
     setMovies(clone);
  }
  
  return (
    &lt;MoviesContext.Provider value={{movies, bookmark}}&gt;
      {children}
    &lt;/MoviesContext.Provider&gt;
  )
} 

Then you wrap your parent component with the provider. Every component using the context should be called as a children of MoviesProvider

&lt;MoviesProvider&gt;
  &lt;Content /&gt;
&lt;/MoviesProvider&gt;

Note that if you use react-router and all your pages will need the context, you can put &lt;Routes /&gt; as a child of &lt;MoviesProvider /&gt;

And then, in every child components, you will have acces to the context with the useContext hook :

const {movies, bookmark} = useContext(MoviesContext);

You can also create a shortcut in your context file

export const useMovies = () =&gt; useContext(MoviesContext)

So you just have to call it that way

const {movies, bookmark} = useMovies()

And that's it !

You can also pass props to the provider if you want to initialize some values from above.

Context in React are very useful so if you want to learn more i suggest you read the documentation :

Also don't hesitate if you have any question, or if my answer doesn't go far enough

答案2

得分: 0

如果您想将数据传递给不同的组件。

您可以使用context、redux-toolkit、zustand等工具。

哪个工具更好?这取决于您的问题。

这取决于项目。

如果您需要处理大量API和不同的API或数据,redux-toolkit是一个不错的选择。

如果您的项目不是大型项目,只是简单或中型项目,useContext是一个不错的选择。

取决于您的项目。

要使用API:

react-query是一个不错的选择。

如果您的项目中有redux-toolkit,您可以使用RTK-Query。

其他选项是axios,可以帮助您管理API。

英文:

if you wanna haved data to diffrent componets .

you can context , redux-toolkit , zustand , and other ..

what tools is better ? this your qustion .

this deppend for project ..

if you need handle so much api and diffrent api or data you redux-toolkit is good option .

if your project is not big project just simpel or medium project useContext is good option .

deppend on your project .

for work with api :

react-query is good option .

if you have redux-toolkit in your project you can use RTK-Query .

other option is axios can help you for manage api

huangapple
  • 本文由 发表于 2023年7月17日 14:50:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定