【问题标题】:How to make a PATCH request in ReactJS如何在 ReactJS 中发出 PATCH 请求
【发布时间】:2021-03-02 05:33:33
【问题描述】:

我正在尝试从我的反应前端向我的 NodeJS API 发送 PATCH 请求。我想要一种情况,如果您单击编辑按钮,初始名称 price 会出现在输入中以进行必要的编辑。然后编辑后,您可以对其进行更新。显示初始数据工作正常,但保存它不起作用。我收到错误消息:“警告:无法对未安装的组件执行 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

【问题讨论】:

  • 你的 api 在 postman 中运行良好吗?
  • 你试过其他方法吗?即 GET、POST
  • API 在 Postman 中运行良好。 GET 和 POST 请求也可以正常工作。 @FirstArachne

标签: node.js reactjs api react-hooks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你的 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
    

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

    【讨论】:

    • 我已经尝试了代码,它仍然没有更新。它也不显示任何错误消息
    • 什么没有准确更新?如果您希望 UI 更新,那么它不会更新,因为您将状态绑定到 defaultValue 而不是 value。
    • 数据库中的数据没有更新,即使在我的控制台上,我收到一条成功消息。
    • 那你能分享一下吗?
    猜你喜欢
    • 2022-11-24
    • 2011-10-14
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2016-08-31
    相关资源
    最近更新 更多