简体   繁体   English

为什么我得到“http://localhost:3000/”? 在反应中使用useNavigate时的路线?

[英]Why am I getting 'http://localhost:3000/?' route when using useNavigate in react?

I am using useNavigate to navigate from one page of my website to another when a button is clicked.单击按钮时,我正在使用useNavigate从我网站的一个页面导航到另一个页面。 When I run the site using npm start, when I click the button, the page reloads the current page and the url changes from 'http://localhost:3000' to 'http://localhost:3000/?'当我使用 npm 开始运行网站时,当我单击该按钮时,页面会重新加载当前页面并且 url 从“http://localhost:3000”更改为“http://localhost:3000/?”

The code is below:代码如下:

const submitForm = async (e) => {
const res = await fetch("http://localhost:8000/properties")
const jsonData = await res.json()
setProperties(jsonData)
navigate("/list", { state: properties })
}

button element:按钮元素:

<button onClick={() => submitForm()}>Find Properties</button>

For configuring my routes in App.js, I simply have:为了在 App.js 中配置我的路由,我只需要:

export default function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <Routes>
          <Route exact path="/" element={<FormComponent />} />
          <Route path="/list" element={<ListComponent />} />
        </Routes>
      </div>
    </BrowserRouter>
  )
}

Issues问题

  1. It seems this button is very likely rendered within a form element, and when the form is submitted the default form action is not being prevented and the page is reloading.看起来这个按钮很可能在form元素中呈现,当提交表单时,默认的表单操作不会被阻止并且页面正在重新加载。

  2. Additionally, it appears the submitForm handler is enqueueing a React state update and then attempting to navigate with the expected updated state.此外,似乎submitForm处理程序正在排队 React state 更新,然后尝试使用预期的更新 state 进行导航。

     const submitForm = async (e) => { const res = await fetch("http://localhost:8000/properties"); const jsonData = await res.json(); setProperties(jsonData); // <-- enqueued state update navigate("/list", { state: properties }); // <-- stale state }

    In React, enqueued state updates are processed asynchronously.在 React 中,排队的 state 更新是异步处理的。 You can't enqueue a state update and expect to read the updated state value in the same function/callback scope the update was enqueued in.您不能将 state 更新排队,并期望在更新排队的同一函数/回调 scope 中读取更新的 state 值。

  3. button elements have type="submit" by default if a type attribute isn't provided.如果未提供type属性,则button元素默认具有type="submit"

Solution解决方案

  1. Move the submitForm callback handler to the form element's onSubmit handler prop.submitForm回调处理程序移动到form元素的onSubmit处理程序道具。
  2. Call preventDefault on the onSubmit event object.onSubmit事件 object 上调用preventDefault
  3. Explicitly declare a button type.显式声明按钮类型。
  4. Pass the fetched JSON data directly in the navigate function, no need to update local state considering the component is likely unmounted soon.直接在navigate function 中传递获取的 JSON 数据,无需更新本地 state 考虑到该组件可能很快就会卸载。

Example:例子:

const submitForm = async (e) => {
  e.preventDefault(); // <-- prevent default form action

  const res = await fetch("http://localhost:8000/properties");
  const jsonData = await res.json();

  navigate("/list", { state: jsonData }); // <-- pass current data
}

...

<form onSubmit={submitForm}>
  ...

  <button type="submit">Find Properties</button>
  ...
</form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在制作客户资料(示例),但在添加数据时出现错误 - POST http://localhost:3000/cusprofiles/add 400 (Bad Request) - I am making a cutomer profile (a sample) and I am getting the error - POST http://localhost:3000/cusprofiles/add 400 (Bad Request) when I add data 为什么我不能在反应中使用 axios 从 localhost:3000 调用 localhost localhost:5000 - Why can't I call localhost localhost:5000 from localhost:3000 using axios in react 我收到此错误“ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login” - I am getting this error “ ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login” 为什么我收到 POST http://localhost:3000/upload 404(未找到)? - Why I'm getting a POST http://localhost:3000/upload 404 (Not Found)? 我在运行 npm 开始使用 reactjs 时在我的本地主机 3000 上得到一个空白页 - I am getting a blank page on my localhost 3000 on running npm start using reactjs 当我尝试打开http:// localhost:3000 / pages / home时出错 - Error when I try to open http://localhost:3000/pages/home 使用服务器而不是本地机器时,我应该用什么替换“http://localhost:3000”? - What do I replace "http://localhost:3000" with when using a server and not local machine? React fetch(&#39;http:// localhost:3000 / profile /:id&#39;) - React fetch('http://localhost:3000/profile/:id') 我不断收到 http POST http://localhost:3000/api/authenticate 404(未找到) - I keep getting http POST http://localhost:3000/api/authenticate 404 (Not Found) 为什么我无法使用反应路由器路由我的应用程序? - Why am I not able to route my app using react router?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM