hooks useState更新对象


点击2个按钮,更新一个state对象,互不影响

 

 

代码:

import React, { useState } from 'react';

export default () => {
  const [state, setState] = useState({
    count: 0,
    count2: 0,
    name: 'aaa',
  });

  const click = () => {
    setState({
      ...state,
      count: state.count + 1,
    });
  };
  const change = () => {
    setState({
      ...state,
      name: 'bbb',
    });
  };
  return (
    <div>
      <div>
        count:{state.count},name:{state.name}
      </div>
      <button onClick={click}>+1</button>
      <button onClick={change}>name</button>
    </div>
  );
};

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM