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

 

posted @ 2020-12-08 16:08  herry菌  阅读(132)  评论(0编辑  收藏