Skip to content

ahooks处理状态

1. 使用useSetState

针对对象的状态值操作,在设置方法中可以只覆盖添加的属性,其他属性不会被删除。之前使用的第三方库immer还支持数组。

jsx
import { Button, Input, Form, Row, Col } from 'antd'
import { useSetState } from 'ahooks'

function App() {
  const [data, setData] = useSetState({ hello: '' })
  const onFinish = (values) => {
    console.log('Success:', values);
    let tempObject = {}
    tempObject[`${values.dataName}`] = values.dataValue
    setData({...tempObject})
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <>
      <Row>
        <Col span={24}>
          <Form
            name="basic"
            labelCol={{
              span: 8
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 600
            }}
            initialValues={{
              remember: true
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="键"
              name="dataName"
              rules={[
                {
                  required: true,
                  message: '请输入键!'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="值"
              name="dataValue"
              rules={[
                {
                  required: true,
                  message: '请输入值!'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">修改或新增</Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </Col>
      </Row>
    </>
  )
}
export default App

运行效果:
Alt text

2. 使用useToggle

useToggle和useBoolean的区别在于:useToggle除了支持true/false还是其他枚举值的切换,useBoolean底层也是通过useToggle来实现的。

jsx
import { Button, Row, Col } from 'antd'
import { useToggle } from 'ahooks'

function App() {
  // 可以只写一个值比如true,底层默认还会生成false选项
  const [state, { toggle, setLeft, setRight }] = useToggle(true)
  return (
    <>
      <Row>
        当前状态: {JSON.stringify(state)}
      </Row>
      <Row>
        <Col span={24}>
          <Button type="primary" onClick={toggle}>转换</Button>
          <Button type="primary" onClick={setLeft} style={{ margin: '0 8px' }}>转换 False</Button>
          <Button type="primary" onClick={setRight}>转换 True</Button>
        </Col>
      </Row>
    </>
  )
}

export default App

执行效果:
Alt text