【问题标题】:ideas to use useAsync hook inside submit function在提交函数中使用 useAsync 钩子的想法
【发布时间】:2021-10-27 19:52:48
【问题描述】:

我已经导入了 useAsync(hook from 'react-async') 并且我正在尝试在客户端提交表单以发送发布请求后使用它。

现在,我收到一个错误,根据钩子的规则,我不能在函数中使用钩子。

怎么解决呢?这样我就可以在客户端提交表单后使用 useAsync 了。 handleSubmit 是我的 onSubmit 函数。

这是我的代码:

import { Modal } from 'react-bootstrap';
import "react-datepicker/dist/react-datepicker.css";
import DatePicker from 'react-datepicker'
import { useState } from 'react';
import { useAsync } from 'react-async';
import useFetch from '../../hooks/useFetch'
import { useLocation } from 'react-router-dom';

const TodoPopup = (props : {show : boolean, onHide : () => void, title : string, values? 
: {title : string, expirationDate : any, description : string}}) => {

const [name, setName] = useState(props.values?.title || '');
const [date, setDate] = useState(props.values?.expirationDate || '');
const [description, setDescription] = useState(props.values?.description || '');

const url = useLocation().pathname;

const handleSubmit = (e : React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  
  // const fetchRelevant = useFetch.apply(this, 
  //   (props.values? [url, 'PUT', {name, date, description}] : [url, 'POST',{name,date, description}]));

    const fetchRelevant = useFetch.apply(this, [url, props.values? 'PUT' : 'POST', 
  {name, date, description}]);

  const { data, error, isPending} = useAsync({promiseFn : () => {
    return fetchRelevant;
  }})

  if(isPending) console.log('loading...');
  if(error) console.log('error');
  if(data)  props.onHide();
}
return (
    <Modal {...props} centered>
  <Modal.Header closeButton>
    <Modal.Title>{props.title}</Modal.Title>
  </Modal.Header>
  <form onSubmit={(e) => handleSubmit(e)}>
  <Modal.Body>
    <div className = "form-group">
        <label>Task Name</label>
        <input type="text" className = "form-control" value = {name} onChange = {(e) => 
     setName(e.target.value)} required />
    </div>
    <div className = "form-group">
        <label>Expired</label>
        <DatePicker selected={date} onChange={e => setDate(e)} className="form-control" 
    minDate={new Date()} required />
    </div>
    <div className = "form-group">
        <label>Description</label>
        <textarea rows = {5} className = "form-control" value = {description} onChange = 
     {(e) => setDescription(e.target.value)}></textarea>
    </div>
  </Modal.Body>
  <Modal.Footer>
    <button className="btn btn-primary" type="submit">Save changes</button>
  </Modal.Footer>
  </form>
</Modal>
);
};

export default TodoPopup;

*注意 - 我尝试使用大写字母命名 onSubmit 函数,但它导致了运行时错误。

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    useFetch 暴露了一个名为 run 的函数,你可以这样调用它:

    import React, { useState } from "react"
    import { useFetch } from "react-async"
    
    const TodoPopup  = (props) => {
    
        const { isPending, error, run } = useFetch("URL", { method: "POST" })
        const [name, setName] = useState(props.values?.title || '');
        const [date, setDate] = useState(props.values?.expirationDate || '');
        const [description, setDescription] = useState(props.values?.description || '');
    
        const handleSubmit = e => {
          e.preventDefault()
          run({ body: JSON.stringify({name, date, description}) })
       }
    
       return (
         <form onSubmit={handleSubmit}>
          ...
         </form>
      )
    }
    
    export default TodoPopup;
    

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 1970-01-01
      • 2017-04-26
      • 2011-10-16
      • 2021-11-04
      • 2020-12-28
      • 2011-12-16
      • 1970-01-01
      • 2012-12-22
      相关资源
      最近更新 更多