how to write a multi lines state with Hooks useState in ReactJs

泪湿孤枕 提交于 2021-02-08 04:31:09

问题


React 16.9

I am aware that this class component 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 component state below using Hooks useState?:

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

Any help would be much appreciated.


回答1:


You can use the same general idea as in class components, 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 complicated 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' });




回答2:


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',
})



回答3:


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.com/whizkydee/react-multi-state/




回答4:


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 compare object's reference value, not comparing the object value. This is different from using React Class component.

reference: https://reactjs.org/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 }));


来源:https://stackoverflow.com/questions/62012191/how-to-write-a-multi-lines-state-with-hooks-usestate-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!