如何在 React Hooks 中将道具更改为状态? [英] How to change props to state in React Hooks?

查看:51
本文介绍了如何在 React Hooks 中将道具更改为状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Simple react 类组件中,我们曾经将 props 更改为这样的状态:

In Simple react class component we used to change the props to state this way:

constructor(props) {
    super(props)

    this.state = {
      pitch: props.booking.pitch,
      email: props.booking.email,
      firstName: props.booking.firstName,
      arrivalDate: props.booking.arrivalDate
    }
} 

但我不知道如何在 Hooks 等新功能中实现,但我正在尝试这样做.

But I am not aware of how to do it in new feature as Hooks, but I am trying to do it this way.

const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(null)

useEffect(() => {
    setDescription(initialDesc)
  }, {})

 function handleChangeVariance(newVariance) {
    setDescription({
      ...description,
      template: {
        ...description.template,
        variance_name: newVariance,
      },
    })
  }

}

基本上,我只需要更改来自另一个父组件的描述道具即可转为状态.请问,你能告诉我如何像 Hooks 那样以新的方式做到这一点吗?

Basically, I just need to change description props, which coming from another parent component to turn to state. Pls, could you show me how to do it in new way as Hooks way?

推荐答案

您可以像这样将初始状态作为第一个参数传递给 useState:

You can pass your initial state as first argument to useState like this:

const GenerateDescHook = ({ description: initialDesc }) => {
  const [description, setDescription] = useState(initialDesc)

  ...

这篇关于如何在 React Hooks 中将道具更改为状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆