使用 Dispatch 函数有条件地渲染组件

时间:2021-03-08 17:49:28

标签: reactjs react-hooks web-audio-api use-context use-reducer

所以我刚刚重构了一个在 react 中使用 useContext/useReducer 创建的应用程序,以便更好地管理状态。我玩得很开心,并且设法让调度功能与您必须选择的位一起工作。
然而。当谈到有条件地呈现开始/停止按钮时,我很困惑。在我的减速器功能中,我有以下内容:

const redFunc = (state, action) => {
switch (action.type) {
case "play": {
  return {
    ...state,
    isPlaying: true,
  };
}
case "stop": {
  return {
    ...state,
    isPlaying: false,
  };
}

通过 React.createContext() 传递给组件。问题是,我真的不明白把 dispatch 函数放在哪里才能让 isPlaying 真正改变。这是我的开始/停止按钮:

  <input
        id="on-off"
        type="button"
        value={isPlaying ? "stop" : "start"}
        onClick={() => togglePlay()}
      />

所以在某处,我想我需要把这行代码放进去,正如我所理解的(如果我错了,请纠正我):

dispatch(isPlaying ? { type: "stop" } : { type: "start" });

这是在我的 togglePlay() 函数中(这绝对是错误的,因为它不起作用......):

  const togglePlay = () => {
if (isPlaying) {
  audioContextRef.current.suspend();
} else {
  audioContextRef.current.resume();
}
dispatch(isPlaying ? { type: "stop" } : { type: "start" });
};

我觉得 dispatch 功能缺少一些基本的东西,但我无法弄清楚,而且我在它上面花了很长时间,以至于我为 Reacty 悲伤而哭泣。当我可以使用 useState()...

时,一切都很棒

帮助...?

0 个答案:

没有答案