【问题标题】:Define reducer inside the component function?在组件函数内部定义reducer?
【发布时间】:2021-07-06 14:18:44
【问题描述】:

在组件的函数(渲染阶段)中定义reducer函数是否有效且安全?

const Component = () => {

  // is this okay to be here or should be outsite the function?
  const reducer = (state, action) => {
    // do stuff
  }

  const [state, dispatch] = React.useReducer(reducer, initState);

  return (
    <div />
  )
}

我想这样做的原因是因为我需要访问组件的道具。如果这种用法不正确,如何访问 reducer 中的 props?

【问题讨论】:

    标签: javascript reactjs use-reducer


    【解决方案1】:

    这不是最佳实践,老实说,我不确定它是否会起作用 - 至少,如果目的是直接访问状态,而不是通过操作传递它。 Redux 的目的是“纯粹的”状态管理。这意味着你接受一个输入(一个“动作”,包含更新 Redux 存储所需的所有状态信息),应用它,然后创建一个新对象来表示程序的状态。

    因此,您无需直接访问状态,而是传递操作中所需的所有变量。

    您可以在此处查看示例代码和一些措辞更仔细的解释: https://redux.js.org/understanding/thinking-in-redux/three-principles

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2020-08-15
      相关资源
      最近更新 更多