javascript - how to write a multi lines state with Hooks useState in ReactJs - Stack Overflow

admin2025-04-19  0

React 16.9

I am aware that this class ponent state:

class JustAnotherCounter extends Component {
  state = {
    count: 0
  };

is the equivalent of using Hooks useState:

function JustAnotherCounter() {
  const [count, setCount] = useState(0);

..but what would be the equivalent of the class ponent state below using Hooks useState?:

class Main extends Component {
    state = {
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    }

Any help would be much appreciated.

React 16.9

I am aware that this class ponent state:

class JustAnotherCounter extends Component {
  state = {
    count: 0
  };

is the equivalent of using Hooks useState:

function JustAnotherCounter() {
  const [count, setCount] = useState(0);

..but what would be the equivalent of the class ponent state below using Hooks useState?:

class Main extends Component {
    state = {
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    }

Any help would be much appreciated.

Share asked May 25, 2020 at 23:13 John DJohn D 2951 gold badge8 silver badges26 bronze badges 1
  • Does this answer your question? Updating and merging state object using React useState() hook – Emile Bergeron Commented May 25, 2020 at 23:33
Add a ment  | 

4 Answers 4

Reset to default 3

You can use the same general idea as in class ponents, just keep in mind that you'll need to spread the object yourself.

   const [state, setState] = useState({
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    });
   // Setting state like:
   setState(prev=>{...prev,firstName:'Joey'});

You can also set up multiple set state calls

const [step,setStep] = useState(1);
const [firstName,setFirstName] = useState('');
const [lastName,setLastName] = useState('');
const [jobTitle,setJobTitle] = useState('');
const [jobCompany,setJobCompany] = useState('');
const [jobLocation,setJobLocation] = useState('');

Another option is to use a reducer, which can be made into a far more plicated example than this:

const [state, dispatch] = useReducer(
  (state, action) => ({ ...state, [action.name]: action.value }),
  {
    step: 1,
    firstName: '',
    lastName: '',
    jobTitle: '',
    jobCompany: '',
    jobLocation: '',
  }
);
// Then update values using:
dispatch({ name: 'firstName', value: 'Joey' });

You can useState to initalize objects like this:

function Main() {
  const [form, setValues] = useState({
      step: 1,
      firstName: '',
      lastName: '',
      jobTitle: '',
      jobCompany: '',
      jobLocation: '',
  })
}

And then to set the values you can do something like

setValues({
    ...form,
    firstName: 'Andrew',
})

Run { npm install react-multi-state } See how easy it is to use

import { Fragment } from 'react'
function Counter() {
  const [state, setState, { setCount }] = useMultiState({
    count: 0,
    secondCount: 10,
  })

  return (
    <Fragment>
      <button onClick={() => setCount(c => c + 1)}>Update count</button>

      <button
        onClick={() => {
          setState(prevState => ({
            secondCount: prevState.secondCount + 10,
            // use as many `prevState` property values as you wish
          }))
        }}
      >
        Update second count
      </button>
    </Fragment>
  )
}

You can easily update the states singly

https://github./whizkydee/react-multi-state/

You can save your state value as an object.

Remember when you update your object value using setState, you MUST create a new object instead of updating existing object's value, because setState pare object's reference value, not paring the object value. This is different from using React Class ponent.

reference: https://reactjs/docs/hooks-faq.html#should-i-use-one-or-many-state-variables

save your state as an object

const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 });
...
// deep clone your object (use other package like lodash or ramda for better performance)
const newObj = JSON.parse(JSON.stringify(state))
// update value and set state
newObj.top = 28
setState(state);

or using spreading for a single line setState

// Spreading "...state" ensures we don't "lose" width and height
setState(state => ({ ...state, left: e.pageX, top: e.pageY }));
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745057839a282510.html

最新回复(0)