【问题标题】:how to write a multi lines state with Hooks useState in ReactJs如何在 ReactJs 中使用 Hooks useState 编写多行状态
【发布时间】:2020-09-12 16:03:02
【问题描述】:

React 16.9

我知道这个class component state:

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

相当于使用 Hooks useState:

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

..但是下面使用 Hooks useStateuseState类组件状态 的等价物是什么?:

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

任何帮助将不胜感激。

【问题讨论】:

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

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

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

您还可以设置多个设置状态调用

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

另一个选择是使用reducer,它可以做成一个比这个复杂得多的例子:

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】:

    你可以像这样使用State来初始化对象:

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

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

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

    【讨论】:

      【解决方案3】:

      运行 { npm 安装反应多状态 } 看看它是多么容易使用

      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/

      【讨论】:

        【解决方案4】:

        您可以将状态值保存为对象。

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

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

        将状态保存为对象

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

        【讨论】:

          猜你喜欢
          • 2019-09-24
          • 2021-01-16
          • 1970-01-01
          • 2021-10-16
          • 2022-01-04
          • 1970-01-01
          • 2020-12-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多