【问题标题】:How can i get some value from other page js?我怎样才能从其他页面js获得一些价值?
【发布时间】:2023-01-07 00:00:14
【问题描述】:

我有两个页面:Header.js 和 Post.js。这些页面加入主页 - Home.js。 Post.js 有按钮“购买”。此按钮创建值为 0 或 1 的变量。此值使用 window.localStorage.setItem() 保存在本地存储中。我想带走价值并给予 Header.js。但是当我点击“购买”时,这个值平均不会更新

我该怎么做?

 window.localStorage.setItem('countcart',count);
  const sumCount = async () => {
    
    if(count === 0){
      setCount(Math.max(count+1,0));
    } else{
      setCount(Math.max(count-1,0));
    }
      
  };

<Button className={styles.buy} onClick={sumCount} variant="contained" endIcon={<ShoppingCartIcon  fontSize="small"/>}><div className={styles.buytext}>Buy</div> </Button>

【问题讨论】:

    标签: javascript reactjs react-hooks react-router


    【解决方案1】:

    如果你希望 localStorage 在每次 count 改变时更新,你应该用 useEffect 包装它:

    useEffect(() => {
      window.localStorage.setItem('countcart',count);
    }, [count])
    

    但是,这不会自动更新其他组件中的计数值;要使用 localStorage 做到这一点,您需要使用 https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event

    但是,其他组件访问 count 的更好方法是将 count 声明为父组件中的状态,并将其状态传递给 Header.jsPost.js 组件,例如:

    // App.js
    function App() {
      const [count, setCount] = useCount(window.localStorage.getItem('count'));
      useEffect(() => {
        window.localStorage.setItem('countcart',count);
      }, [count])
      return (
        <>
           <Header count={count} setCount={setCount} />
           <Post count={count} setCount={setCount} />
        </>
      )
    }
    

    【讨论】:

    • 我需要 Header 中的 setCount 做什么?
    • setCount 是 React 知道 count 变量改变的方式;否则 Header.js 不知道 count 变量已经更新,它最终不会在 Header.js 组件中更新。
    • 好的谢谢。我会尝试
    • 对不起,我是这门语言的大三学生。我不明白有什么问题。 Post.js 对我说 setCount 不是一个函数。你能帮我吗?
    • 您可以发送您的Post.js 组件的完整代码吗?
    【解决方案2】:

    import {Routes, Route} from 'react-router-dom';
    import Container from '@mui/material/Container';
    
    
    import { Header } from './components';
    import { Home, FullPost, Registration, AddPost, Login, PostsByTag, Account } from './pages';
    import { useDispatch, useSelector } from 'react-redux';
    import React, { useState } from 'react';
    import { fetchAuthMe, selectIsAuth } from './redux/slices/auth';
    
    
    
    
    function App() {
      const dispatch = useDispatch();
      const [count, setCount] = useState(window.localStorage.getItem('countcart')? 0 :window.localStorage.getItem('countcart'));
      const isAuth = useSelector(selectIsAuth);
      React.useEffect(()=>{
        dispatch(fetchAuthMe());
        window.localStorage.setItem('countcart',count);
      },[count])
      
      return (
        <>
          <Header count={count} setCount={setCount}/>
          <Container maxWidth="lg">
            <Routes>
            <Route path="/" element={<Home count={count} setCount={setCount}/>} />
            <Route path="/posts/:id" element={<FullPost />} />
            <Route path="/tags/:tag" element={<PostsByTag />} />
            <Route path="/posts/:id/edit" element={<AddPost />} />
            <Route path="/add-post" element={<AddPost />} />
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Registration />} />
            <Route path="/account/:id" element={<Account />} />
            </Routes>
          </Container>
        </>
      );
    }
    
    export default App;

    import React from 'react';
    import { Rating,IconButton, Button} from '@mui/material';
    import clsx from 'clsx';
    import {Link, useNavigate} from 'react-router-dom';
    import DeleteIcon from '@mui/icons-material/Clear';
    import EditIcon from '@mui/icons-material/Edit';
    import EyeIcon from '@mui/icons-material/RemoveRedEyeOutlined';
    import CommentIcon from '@mui/icons-material/ChatBubbleOutlineOutlined';
    import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
    import styles from './Post.module.scss';
    // import { UserInfo } from '../UserInfo';
    import { PostSkeleton } from './Skeleton';
    import { useDispatch } from 'react-redux';
    import { fetchRemovePost } from '../../redux/slices/posts';
    
    
    export const Post = ({
      id,
      title,
      createdAt,
      imageUrl,
      user,
      viewsCount,
      commentsCount,
      tags,
      children,
      isFullPost,
      isLoading,
      isEditable,
      count,
      setCount,
    }) => {
      // const [count, setCount] = React.useState(0);
      const dispatch = useDispatch();
      const navigate = useNavigate();
      
      if (isLoading) {
        return <PostSkeleton />;
      }
      console.log(count);
      window.localStorage.setItem('countcart',count);
      const sumCount = async () => {
        
        if(count === 0){
          setCount(Math.max(count+1,0));
        } else{
          setCount(Math.max(count-1,0));
        }
          
      };
    
      const onClickRemove = () => {
        if(window.confirm('Do you sure want to remove post?')){
          dispatch(fetchRemovePost(id));
          navigate(0);
          
      }
     
      };
      return (
        <div className={clsx(styles.root, { [styles.rootFull]: isFullPost })}>
          {isEditable && (
            <div className={styles.editButtons}>
              <Link to={`/posts/${id}/edit`}>
                <IconButton color="primary">
                  <EditIcon />
                </IconButton>
              </Link>
              <IconButton onClick={onClickRemove} color="secondary">
                <DeleteIcon />
              </IconButton>
            </div>
          )}
          {imageUrl && (
            <img
              className={clsx(styles.image, { [styles.imageFull]: isFullPost })}
              src={imageUrl}
              alt={title}
            />
          )}
          <div className={styles.wrapper}>
            <div className={styles.indention}>
              <h2 className={clsx(styles.title, { [styles.titleFull]: isFullPost })}>
                {isFullPost ? title : <Link to={`/posts/${id}`}>{title}</Link>}
              </h2>
              <div className={styles.ratingprice}>
                    <Rating 
                        name="size-small"
                        value={2.5}
                        size="small"
                        precision={0.5}
                        readOnly 
                      /> 
                      <div className={styles.review}>12 отзывов</div>
              </div>
              <div className={styles.price}>1150 руб.</div>
              {children && <div className={styles.content}>{children}</div>}
              <div className={styles.postDetails}>
                      <ul className={styles.postDetails}>
                        <li>
                          <EyeIcon />
                          <span>{viewsCount}</span>
                        </li>
                        <li>
                          <CommentIcon />
                          <span>{commentsCount}</span>
                        </li>
                      </ul>
    
                      <Button className={styles.buy} onClick={sumCount} variant="contained" endIcon={<ShoppingCartIcon  fontSize="small"/>}><div className={styles.buytext}>Купить</div> </Button>
    
              </div>
            </div>
          </div>
        </div>
    
      );
    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多