【问题标题】:How to manage useReducer with other setState and how to manage unpure manipulation like DOM focus?如何使用其他 setState 管理 useReducer 以及如何管理像 DOM 焦点这样的不纯操作?
【发布时间】:2019-12-12 23:07:41
【问题描述】:

我读过reducer 应该是纯函数。

然后我有两个问题:如何管理其他 setState,如果它们与减速器链接?以及如何处理像焦点 HTML 元素这样的 DOM 操作?

为了说明这一点,这是我使用不纯 reducer 的代码:

const ActDeclaration = () => {
   const [errors, setErrors] = useState({})
   const refPersonType = useRef()

   const reducer = (state, action) => {
      switch (action.type) {
         case "internalNumber":
            return { ...newState, internalNumber: action.payload }
         case "profile": {
            setErrors({}) // HERE
            const errors = hasErrors(newState, setErrors)

            if (!isEmpty(errors)) {
               setErrors(errors) // HERE

               refPersonType.current.scrollIntoView({ // HERE
                  behavior: "smooth",
                  block: "start",
               })
            }
            return newState
         }
         default:
            return newState
      }
   }

   const [state, dispatch] = useReducer(reducer, {})

我使用setErrors 来修改负责显示/管理错误的状态变量。

这可能会产生副作用吗?实际上,reducer 中的 setErrors 是否会触发重新渲染?

在reducer的内部状态中管理错误状态对我来说并不理想,因为setErrors也被一个不依赖reducer的提交函数调用,这就是为什么我发现将错误分开是个好主意。

第二个问题,ref 焦点。我怀疑这也是一个副作用。如何处理?我是这样做的,因为我有一个按钮,它在单击事件时调用调度函数等等,reducer 函数。因此,reducer 似乎是做焦点工作的合适人选。

感谢您的意见!

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    对于profile 操作来检查错误并同时在其中滚动似乎是一个错误的位置。

    您可以在 useEffect 内的 reducer 之外或在事件处理程序内执行此操作,因为 profile 没有进行状态操作。

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      相关资源
      最近更新 更多