How to change props to state in React Hooks?

前端 未结 4 1659
温柔的废话
温柔的废话 2021-02-02 07:41

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

constructor(props) {
    super(props)

    this.state = {
      pitch: props.book         


        
4条回答
  •  抹茶落季
    2021-02-02 08:15

    The initial value of your state is the one passed into useState :

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

    As the documentation states :

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

    You clicked {count} times

    ); }

    Is the equivalent of :

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

    You clicked {this.state.count} times

    ); } }

提交回复
热议问题