【问题标题】:React Hooks - What is the recommended way to initialize state variables with useState() from propsReact Hooks - 使用 props 中的 useState() 初始化状态变量的推荐方法是什么
【发布时间】:2022-07-09 19:49:22
【问题描述】:

我在问是否有(如果有,什么是)推荐的方法来使用来自 props 的值初始化 React 挂钩中的状态变量。

所以我假设我有一个这样的组件:

function SomeComponent(props) {
    return (
        ....
    );
}

我可以使用useState为这个组件创建一个变量,像这样:

const [someVariable, setSomeVariable] = useState('someValue');

到目前为止一切顺利。 我现在的问题是,如果我想用 props 中的值初始化变量,是否建议直接这样:

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(props.someValue);
}

或者最好用null初始化它,然后用useEffect()在加载时设置值:

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(null);

    useEffect(() => {
        setSomeVariable(props.someValue);
    },[])
}

也许还有更多方法。我只是想知道这里是否有建议,或者最终您使用哪种方式并不重要。

【问题讨论】:

  • sameValue 多久更改一次?
  • 嗯,好的。感谢您的评论。这也应该被考虑。谢谢!

标签: reactjs react-hooks


【解决方案1】:

您应该采用第一种方法。这是标准的、惯用的 React 方式。

function SomeComponent(props) {
    const [someVariable, setSomeVariable] = useState(props.someValue);
}

useEffect 方法也可以,但您没有任何理由这样做,更不用说组件第一次渲染时的状态将是 null

【讨论】:

    【解决方案2】:

    最好使用useState(props.someValue) 而不是在useEffect 中设置它,因为useEffect 是在 react 完成渲染组件之后执行的,这样做会触发重新渲染,因为你是设置一个新的状态。如果您将其设置为useState,您将能够避免额外的重新渲染。

    编辑:根据组件的逻辑,您可能必须在组件中处理 null 状态,以防您在 useEffect 中执行此操作

    【讨论】:

      【解决方案3】:

      如果props没有变化,则不需要使用useState

      如果发生变化,请执行以下操作:

      function SomeComponent(props) {
          const [someVariable, setSomeVariable] = useState(props.someValue);
      
          useEffect(() => {
              setSomeVariable(props.someValue);
          },[props.someValue])
      }
      

      阅读此问题和答案以了解您为什么需要这样做。

      React.useState does not reload state from props


      我会这样做:

      function SomeComponent({someValue}) {
          const [someVariable, setSomeVariable] = useState(someValue);
      
          useEffect(() => {
              setSomeVariable(someValue);
          },[someValue])
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-07
        • 2020-02-24
        • 2023-03-08
        • 2010-09-24
        • 2023-03-19
        相关资源
        最近更新 更多