繁体   English   中英

如何在 ReactJs 中使用 Hooks useState 编写多行 state

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

React 16.9

我知道这个class component state

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

相当于使用HookuseState

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

..但是下面使用Hooks useStateclass 组件 state的等价物是什么?:

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

任何帮助将非常感激。

您可以使用State 来初始化对象,如下所示:

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

然后设置值,您可以执行类似的操作

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

您可以使用与 class 组件相同的一般概念,但请记住,您需要自己传播 object。

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

您还可以设置多组 state 调用

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('');

另一种选择是使用减速器,它可以做成一个比这更复杂的例子:

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

运行 { npm install react-multi-state } 看看它是多么容易使用

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

您可以轻松地单独更新状态

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

您可以将 state 值保存为 object。

请记住,当您使用 setState 更新 object 值时,您必须创建一个新的 object而不是更新现有对象的值,因为 setState 比较对象的参考值,而不是比较 object 值。 这与使用 React Class 组件不同。

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

将您的 state 保存为 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);

或对单行 setState 使用传播

// Spreading "...state" ensures we don't "lose" width and height
setState(state => ({ ...state, left: e.pageX, top: e.pageY }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM