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

React点击时数组被清空问题求助:电影选择匹配功能异常

问题分析与解决方案

核心问题

  • setUserChoices回调未返回更新值:你的handleObjectSelect里,setUserChoices的回调函数创建了updatedChoices但没有返回它,导致React把userChoices设置为undefined,后续数组操作自然异常,看起来像是被清空了。
  • 未重置选择数组:当选中2部电影完成对比后,没有重置userChoices,导致后续点击会继续往数组里追加元素,逻辑混乱。

修正后的代码

const [userChoices, setUserChoices] = useState([]);

useEffect(() => {
    if (userChoices.length === 2) {
        console.log(userChoices);
        if (userChoices[0] === userChoices[1]) {
            console.log('W');
        } else {
            console.log('L');
        }
        // 对比完成后重置选择数组,允许用户重新选择
        setUserChoices([]);
    }
}, [userChoices]);

const handleObjectSelect = (selectedObject) => {
    // 最多只存2个选择,避免数组无限增长
    if (userChoices.length >= 2) return;
    
    setUserChoices((prevChoices) => {
        // 必须返回更新后的数组
        return [...prevChoices, selectedObject];
    });
};

return (
    <div className="content-card" onClick={() => handleObjectSelect(movie?.title)}>
        <img className="movie-poster img-fluid" src={`${img500x500}/${movie?.poster_path}`} />
        <div className="movie-title">{movie?.title}</div>
        <div className="movie-info">
            <span>{movie?.release_date}</span>
            <span><FontAwesomeIcon icon={faStar} />{movie?.vote_average}</span>
        </div>
    </div>
);

关键修改说明

  • 修复setUserChoices回调:在回调函数中返回updatedChoices,确保state能正确更新为新数组。
  • 添加数组长度限制:在handleObjectSelect里判断如果已经选了2部,就不再添加,避免数组越界。
  • 重置选择数组:在useEffect的对比逻辑结束后,调用setUserChoices([])清空数组,让用户可以进行下一轮选择。
  • 放弃普通变量存储:React组件中必须用state存储需要触发重渲染的状态,普通变量不会触发组件更新,所以之前用普通数组的尝试无效是正常的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:50:02