如何在 useState 中传递 const

How to pass const inside useState in react

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

下面的代码在class构造函数中我想把它转换成功能组件

Class 分量:

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

如何在功能组件中执行上述操作?

您可以为使用状态挂钩添加一个默认值。传个道具就行了

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

如果你想在 prop 改变时重置状态,在依赖数组中设置一个 useEffect 挂钩与相应的 props,并用新值设置状态。

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

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

阅读更多关于钩子用法的信息here

无需使用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;

你可以像这样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;
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