我有一个蚂蚁表单,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.
如果我在onFinsh
函数外部编写useEffect钩子,则无法获取表单数据/值
请提出一种解决方法,以获取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'));
看起来您甚至不需要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>);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句