【问题标题】:How to pass const inside useState in react如何在useState中传递const
【发布时间】:2022-01-23 11:16:36
【问题描述】:

我有一个代码需要在 useState 中传递一个 const 有人可以帮忙吗??

以下代码在类构造函数中,我想将其转换为功能组件

类组件:

     constructor(props){
     super(props);
     const {id, name, email} = props.location.state.contact;
     this.state={
                 id,
                 name,
                 email
                 }

如何在功能组件中做到这一点?

【问题讨论】:

  • 1.我建议使用功能组件。作为初学者,您将拥有更少的开销。你能提供你完整的类组件代码吗?
  • 从 'react' 导入 {useState} 然后 const [name,setName] = useState("")

标签: reactjs use-state react-functional-component


【解决方案1】:

不用useState就可以在函数组件内部解构得到props

import React from 'react';

function Test(props) {

    // destructuring
    const { id, name, email } = props;
    return (
        <div>
          ...
        </div>
    )
}

export default Test;

但是如果你想使用useState:

import React, { useState } from 'react';

function Test(props) {

    const [state, setState] = useState(props.location.state.contact);
    return (
        <div>
          ...
        </div>
    )
}

export default Test;

【讨论】:

    【解决方案2】:
    import React, { useState } from "react";
    
    const Component = (props) => {
      const [state, setState] = useState(props.location.state.contact);
    
      
      return <div></div>;
    };
    
    export default Component;
    

    使用示例编写沙箱代码: https://codesandbox.io/s/upbeat-framework-li4rb?file=/src/Component.js

    【讨论】:

      【解决方案3】:

      你可以像这样使用function component

      import React, {useState} from 'react';
      
      function myComponent(props) {
      
          const {id, name, email} = props.location.state.contact;
          const [stateValue, setStateValue] = useState({id, name, email});
      
          return (
             ....
          )
      }
      
      export default myComponent;
      

      【讨论】:

      • @Devanshu Desai 如果有帮助,请支持我的回答
      【解决方案4】:

      您可以为使用状态挂钩添加默认值。只是传递道具。

      function Component(props) {
        const {location:{ state: { contact: { id, name, email } } }} = props;
        const [state, setState] = useState({id, name, email});
      }
      

      如果您想重置道具更改的状态,请使用依赖数组中的相应道具设置useEffect 挂钩,并使用新值设置状态。

      【讨论】:

        【解决方案5】:

        我相信你可以做到以下几点

        function Component(props) {
          const [state, setState] = useState(props.location.state.contact);
          // state will have id, name, and email
          return <></>
        }
        

        阅读更多关于 hooks 的使用here

        【讨论】:

          猜你喜欢
          • 2021-12-02
          • 1970-01-01
          • 1970-01-01
          • 2021-04-30
          • 2021-04-23
          • 1970-01-01
          • 2015-11-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多