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

Redux useSelector不更新值、不触发useEffect问题求助

问题解决:useSelector获取Redux状态不更新的问题

核心问题

你的useSelector回调函数没有返回值,导致每次获取的都是undefined,自然不会触发依赖更新。

修正后的组件代码

将useSelector中的回调改为返回目标状态值:

import { store } from "../pages/_app";
....
  const dispatch = useDispatch();
  const [state_sample, setSs]: any = useState(0);
  // 修正:直接返回状态值(去掉多余的花括号或添加return)
  const audioCurrentTimeState: any = useSelector((state: RootState) => 
    state.AudioCurrentTimeState
  );

  useEffect(() => {
    console.log(audioCurrentTimeState); // 现在会正常输出更新后的值
    console.log(store.getState().AudioCurrentTimeState);
  }, [audioCurrentTimeState, state_sample]);

  return (
    <div className={style.waveform_component_root}>
      <p
        onClick={() => {
          console.log("clicked!");
          setSs(Math.random());
          dispatch({
            type: "AudioCurrentTimeReducer/SET",
            value: Math.random(),
          });
        }}
      >
        click me
      </p>
   </div>)

原因说明

  • 原代码中useSelector的回调仅写了state.AudioCurrentTimeState;语句,没有返回值,默认返回undefined。
  • 无论Redux状态如何变化,useSelector拿到的始终是undefined,依赖数组中的audioCurrentTimeState没有变化,因此useEffect不会触发。
  • store.getState()是直接从Redux store读取最新状态,所以能拿到正确值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:41:18