微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 ReactJS 中发出 PATCH 请求

如何解决如何在 ReactJS 中发出 PATCH 请求

我正在尝试从我的 React 前端向我的 NodeJS API 发送 PATCH 请求。我想要一种情况,如果您单击编辑按钮,初始名称价格会出现在输入中以进行必要的编辑。然后编辑后,您可以更新它。显示初始数据工作正常,但保存它不起作用。我收到错误消息:“警告:无法对卸载的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 中的所有订阅和异步任务清理功能。” 我已经查找了清理功能,但无法取得进展。 下面是我的代码

const EditUserForm = () => {
  const history = useHistory();
  const match = useRoutematch();
  let routeId = match.params.id;
  console.log(routeId);

  const [error,setError] = useState(null);
  const [isLoaded,setIsLoaded] = useState(false);
  const [item,setItem] = useState({});

  const [name,setName] = useState();
  const [price,setPrice] = useState();

  const handleInputChange = (e) => {
    console.log(e.target.value)
    const { name,value } = e.target;
    setItem({ ...item,[name]: value});
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    updateProduct();
    history.push('/');
  }
   
  const updateProduct = () => {
    fetch(`/addproducts/${routeId}`,{
      method: 'PATCH',headers: {
        'Content-Type': 'application/json',},body: JSON.stringify({
        name: item.name,price: item.price 
      }),})
      .then((res) => res.json())
      .then((result) => setItem(result))
      .catch((err) => console.log('error: ',err))
      
  }

  useEffect(() => {
    fetch(`/products/${routeId}`,requestOptions)
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setName(result.product.name);
          setPrice(result.product.price);
        },(error) => {
          setIsLoaded(true);
          setError(error);
        }
      )

  },[]);

  return (        
    <form onSubmit={handleSubmit} >
      <label>Name</label>
      <input 
        type="text"
        name="name"
        defaultValue={name}
        onChange={handleInputChange} 
      />

      <label>Price</label>
      <input 
        type="text" 
        name="price" 
        defaultValue={price}
        onChange={handleInputChange}
      />

      <button type="submit">Update</button>
      <button>
        Cancel
      </button>
    </form>
  )
}

export default EditUserForm

解决方法

在“handleSubmit”中,您正在调用“history.push('/')”,这会产生错误,如果您想更改路由,请调用它.thenupdateProduct

,

您的 useEffect 函数应用于每个渲染并且不可取消,尝试像这样重写它

useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;
    fetch(`/products/${routeId}`,{signal,...requestOptions})
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setName(result.product.name);
          setPrice(result.product.price);
        },(error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
      return controller.abort //so the fetch request can be canceled if the effect is re-executed
  },[routeId]); //only needs to rerun on route change

我不太确定句柄提交是否会导致类似的问题,在这种情况下,您可能想要做类似的事情。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?