React functional component using state

后端 未结 4 1757
生来不讨喜
生来不讨喜 2020-12-06 11:30

I\'m trying to implement a React smart component using functions as shown here https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlook

相关标签:
4条回答
  • 2020-12-06 12:04

    Stateless Functional Components can't have state, you will need to use a regular React Component if you want to have state within the component.

    0 讨论(0)
  • 2020-12-06 12:07

    If you want to use state in the functional component, then there is one package called recompose, which provides a set of helper functions for stateless function components. There is withState() helper that enables state.

    0 讨论(0)
  • 2020-12-06 12:24

    Stateless functional components are intended to be presentation-oriented, since they can't have local UI state within themselves. This is great though, because without the ability to have internal state, the use of pure functional components promotes better use of the single responsibility principle through out your app, allowing simpler components each focused on doing less stuff. A win for designing software that becomes less of a headache to maintain and add features to later.

    Stateless functional components are passed in state from a Container component and are responsible for rendering the state passed in to them via props from their Container component. This allows the Container component to have a simpler, more focused responsibility for getting and transforming data to pass to the stateless functional components. The pure functional components abstract out the details of rendering JSX from the Container.

    So long story, what you want is a container component class so you have can create relevant UI state and manage it in the React lifecycle methods, which you do not have access to in a pure functional component.

    0 讨论(0)
  • 2020-12-06 12:29

    From React 16.8.0 You can use Hooks using useState to instantiate a State custom in your Functional Component. Like This...

    import React, {useState} from 'react';
    
    const AddButon = ({handleAddValue}) => {
      return <button onClick={handleAddValue}>Add</button>
    }
    
    const App = (props) =>{
    
      const [value, setValue] = useState(0);
    
      const handleAddValue = () => {
        const newValue = value+1;
        setValue(newValue);
      }
    
      return (
        <div>
          <div>The Value is: {value}</div>
          <AddButon handleAddValue={handleAddValue} />
        </div>);
    }
    

    If you want to read more about this new functionality, follow the following link.

    https://reactjs.org/docs/hooks-intro.html

    0 讨论(0)
提交回复
热议问题