You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在移动端与桌面端模式下设置不同的useState值?

Fix for Dynamic Products Per Page Based on Screen Size

Hey there, let's get this issue sorted out right away—you're so close to making this work! The problems in your code are easy to fix, so let's break them down step by step:

1. The Typo That's Breaking State Updates

First off, you have a small but critical typo in your useEffect: you're calling setPostsPerPage(8) but your state setter is actually named setProductsPerPage. That's why your state never updates when the screen size changes—you're referencing the wrong function entirely!

2. Incomplete Logic for Desktop View

Right now, your code only handles the mobile screen case (setting to 8 products), but it never resets the count back to 12 when switching back to a desktop screen. That means once you go mobile, you'll stay stuck at 8 products even when resizing up.

Corrected Working Code

Here's the fixed version that will handle both mobile and desktop correctly:

import { useState, useEffect } from 'react';
// Adjust the import based on your media query library (MUI, react-responsive, etc.)
import { useMediaQuery } from '@mui/material';

const YourProductComponent = () => {
  const [productsPerPage, setProductsPerPage] = useState(12);
  // Standard CSS media query syntax (wrap in parentheses for most libraries)
  const isMobile = useMediaQuery('(max-width: 600px)');

  useEffect(() => {
    if (isMobile) {
      setProductsPerPage(8);
    } else {
      // Reset to desktop count when screen size increases
      setProductsPerPage(12);
    }
  }, [isMobile]); // Trigger effect every time the screen size status changes

  // Rest of your component logic (rendering products, pagination, etc.)
  return (
    <div>
      {/* Your product grid/render logic using productsPerPage */}
    </div>
  );
};

export default YourProductComponent;

Even Cleaner Alternative (No useEffect Needed!)

You can simplify this further by directly deriving the value instead of managing a separate state variable. This avoids the need for useEffect entirely, since the value will automatically update when the screen size changes:

const isMobile = useMediaQuery('(max-width: 600px)');
const productsPerPage = isMobile ? 8 : 12;

This approach is more efficient because it cuts out the extra state management and syncing logic.

内容的提问来源于stack exchange,提问作者QPAO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:13:12