0

我有一个antd 表单,我可以onFinish function在点击提交按钮时获取表单数据,我想在其中使用uesEffect hook表单数据作为有效负载的动作并将其发送到 redux saga,但出现以下错误

React Hook "useEffect" is called in function "onFinish" that is neither a React function component nor a custom React Hook function.

如果我在函数外部编写 useEffect 钩子onFinsh,我将无法获取表单数据/值


请建议一种解决方法以在 onFinish 函数之外获取表单数据值


import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox } from 'antd';
 

const Demo = () => {
  const onFinish = (values) => {
    // alert(JSON.stringify(values['username']));
    useEffect(() => {
      // dispatch an action with values as payload
     }, []);
  };
console.log(values) // UNABLE TO GET VALUES HERE...HOW TO GET IT???
  return (
    <Form
      name="basic"
      onFinish={onFinish}>
      <Form.Item
        label="Username"
        name="username">
        <Input />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, document.getElementById('container'));
4

2 回答 2

3

看起来你甚至不需要useEffect()钩子。只需从内部调度动作onFinish()并让状态存储values

const Demo = () => {

  const [ values, setValues ] = useState([]);
  
  const onFinish = (recievedValues) => {
    // dispatch here
    setValues(recievedValues);
  }
  
  console.log(values) // <-- you can get it here
  return (<div> ... </div>);
};

或者更好的是,由于您已经在调度期间将值保存在 redux 中,因此您也应该在渲染代码中使用它:

import { useSelector } from 'react-redux';

const Demo = () => {

  //point to the state where your data is
  const stateValues = useSelector(state => state.your.data);
  
  const onFinish = (recievedValues) => {
    // dispatch here
  }
  
  console.log(stateValues) // <-- you can get it here
  return (<div> ... </div>);
};

于 2021-01-20T18:01:28.647 回答
2

useEffect 只能在组件的顶层调用,不能在函数内调用。在这种情况下,您不需要 useEffect 来调度操作,而是可以直接在 onFinish 内部执行。

于 2021-01-20T18:00:23.053 回答