简体   繁体   English

重新加载页面时,React Context 值消失

[英]React Context value disappears when reloading page

I successfully fetch data of a movie inside useEffect().我在 useEffect() 中成功获取了电影的数据。 However, when the page is reloaded, the value const { selectedMovie } = useContext(MoviesContext) disappears and 404 errors are printed out in the console (since the default value 0 is being used and incorrect called to API is being done).但是,当页面重新加载时,值const { selectedMovie } = useContext(MoviesContext)消失并且在控制台中打印出 404 错误(因为正在使用默认值0并且正在执行对 API 的错误调用)。

This is the component that is reloaded:这是重新加载的组件:

import {useState, useEffect, useContext} from "react";
import Topbar from '../Header/Topbar';
import { fetchSelectedMovie } from "../../services/movies.service";
import {Grid, Card, CardMedia} from '@material-ui/core';
import noImage from '../../images/no-image-available.png';
import { MoviesContext } from "../../services/context";
import './Pages.css';
const posterBaseUrl = "https://image.tmdb.org/t/p/w300";
interface Genre {
  id: number;
  name: string;
}
interface Movie {
  id: number;
  title: string;
  vote_average: number;
  overview: string;
  poster_path?: string;
  release_date: string;
  budget: number;
  revenue: number;
  genres: Genre[];
}

const MoviePage = (props: any) => {

  const { selectedMovie } = useContext(MoviesContext);

  const [movie, setMovie] = useState<Movie>(
    {
      id: 0,
      title: '',
      vote_average: 0,
      overview: '',
      poster_path: noImage,
      release_date: '',
      budget: 0,
      revenue: 0,
      genres: [],
    }
  );
  const [movieImg, setMovieImg] = useState<string>(noImage);

  useEffect(() => {
    const callAPI = async () => {
      const fetchedMovieInfo = await fetchSelectedMovie(Number(selectedMovie));
      setMovie(fetchedMovieInfo);
      setMovieImg(posterBaseUrl+fetchedMovieInfo.poster_path);
    }

    callAPI();
  }, [selectedMovie]);

  return (
    <>
      <Topbar></Topbar>
      <Grid container spacing={2} className="container-movie-page">
        <Grid item xs={6} sm={3}>
          <Card className="card">
            <CardMedia
              component="img"
              alt={"Poster of " + movie.title}
              image={movieImg}
              title={movie.title}
            />
          </Card>
        </Grid>
        <Grid item xs={6} sm={9} className="align-left">
          <h1 className="title">
            {movie.title}
          </h1>
        </Grid>
    </>
  );
}

export default MoviePage;

React Context that is used:使用的反应上下文:

import React from "react";
import { Movie } from "./movies.service";

export const MoviesContext = React.createContext<{
    movies: Movie[];
    updateMovies: Function;
    selectedMovie: number;
    setSelectedMovie: (value: number) => void;
  }>({
    movies: [],
    updateMovies: Function,
    selectedMovie: 0,
    setSelectedMovie: () => {},
  });

These are 404 errors I receive:这些是我收到的 404 错误:

在此处输入图片说明

What changes should be made?应该做哪些改变?

Indeed, State is lost with React when you Refresh the page as it is no persistent.事实上,当您刷新页面时,由于 React 没有持久性,State 会丢失。

You should use another method to keep this information even if the user refresh the page.即使用户刷新页面,您也应该使用另一种方法来保留此信息。 Here are the options:以下是选项:

  • In the database.在数据库中。 Could work if the user is behind an authentification (Login password).如果用户支持身份验证(登录密码),则可以工作。 Example User name: Paul , id; 3131示例用户name: Paul , id; 3131 id; 3131 , did click on the button "connect". id; 3131 ,确实点击了“连接”按钮。 In your database, you add a column in the table User called userConnect = true在您的数据库中,您在名为userConnect = true的表User添加一列
  • In the url.在网址中。 As soon as the user click on the button "connect" you change the URL with React router .一旦用户单击“连接”按钮,您就可以使用React router更改 URL。 For example the URL was mydomain.com , and after clicking it becomes mydomain.com?clicked=true .例如,URL 是mydomain.com ,点击后变为mydomain.com?clicked=true If the user refresh your page, you still have the information about the user who clicked on the button.如果用户刷新了您的页面,您仍然拥有有关单击该按钮的用户的信息。
  • In a cookie (More info here https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies )在 cookie 中(更多信息在这里https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
  • In local Storage (More info here https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local )在本地存储中(更多信息在这里https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local

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

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