【问题标题】:React - How to update my component when there is a change on the serverReact - 当服务器发生变化时如何更新我的组件
【发布时间】:2022-02-05 01:05:03
【问题描述】:

我想在 put 请求成功时重新加载页面,但它从不重新加载页面。有什么问题

async function saveEdit() {
        await Axios.put('http://localhost:5000/edit', {id: id, newTitle: title, newDescription: description, newImageURL: imageURL});
        window.location.reload();
       
        
    }

请求有效,但reload() 行似乎无效。还是有更好的方法来做到这一点?

【问题讨论】:

  • 试试window.location.reload(true);
  • 我还想补充一点,当服务器发生变化时更新组件的最佳方法是使用状态并更新状态,而不是重新加载整个页面。
  • @JaivBhup 仍然不起作用?我很困惑
  • mongodb数据库有变化时如何使用,useState来改变组件
  • 尝试使用window.location.href = window.location.href

标签: node.js reactjs mongodb


【解决方案1】:

useState() 钩子在 react 中的简单实现

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [data, setData] = useState(null);
  async function saveEdit(id, title, description, imageURL) {
        // Make sure that your request responds back with the relevant and fresh batch of data after the update
        var res = await Axios.put('http://localhost:5000/edit', {id: id, newTitle: title, newDescription: description, newImageURL: imageURL});
        //window.location.href = window.location.href;
        var data = res.data;
        setData(data)
    }
  return (
    <div>
       {data?.map(d=>{
           // How you want to processes your data object.
           return <h1>d.title</h1>
        })}
        <button onClick={()=>saveEdit(1,"Mytitle","description","test Url")}> Update </button>
    </div>
  );
}

有关反应挂钩的更多信息,请参阅here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多