如何在React Hooks中将道具改为状态?

问题描述 投票:7回答:3

在Simple react类组件中,我们用这种方式将props更改为:

constructor(props) {
    super(props)

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

但我不知道如何在Hooks这样的新功能中做到这一点,但我试图这样做。

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

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

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

}

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

reactjs react-hooks
3个回答
11
投票

您可以将初始状态作为第一个参数传递给useState,如下所示:

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

  ...

7
投票

问题出在{};

你应该这样做,每次initialDesc改变时同步状态和描述:

useEffect(() => {
    setDescription(initialDesc)
  }, [initialDesc]); // Only rerun if initialDesc changes

见:React docs: Tip: Optimizing Performance by Skipping Effects


1
投票

您的州的初始值是传递给useState的值:

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

正如documentation所述:

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

相当于:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.