【发布时间】:2021-06-18 01:12:26
【问题描述】:
我正在使用 react.js 作为我的前端,现在正在处理一个组件。用于创建新数据并显示所有数据。
我正在使用 http://localhost:3000/locations screenshot before create
创建数据成功后,突然url变成了 http://localhost:3000/locations**?** screenshot after create 我想知道这是哪里?问号来自,我也注意到我的浏览器控制台日志,页面每次都在重新加载
我用npx create-react-app启动文件,只修改了App.js和Location.js
查看 App.js enter image description here
查看 Location.js 的代码
import React, {useState, useEffect} from 'react'
import axios from "axios"
export default function Location() {
const [locations, setLocations] = useState([])
const [locationname, setLocationname] = useState("")
const [latitude, setLatitude] = useState("")
const [longitude, setLongitude] = useState("")
const createNewLocation = () => {
const createLocation = async () => {
const {data} = await axios.post("/api/locations", {locationname, coordinates: {latitude, longitude}} ,{headers: {"content-type": "application/json"}})
console.log("data", data)
setLocationname(locationname)
setLatitude(latitude)
setLongitude(longitude)
}
console.log("the click")
createLocation()
}
useEffect(()=>{
const getLocations = async() => {
const {data} = await axios.get("/api/locations", {headers: {"content-type": "application/json"}})
console.log(data)
setLocations(data)
}
getLocations()
}, [])
return (
<div>
<form onSubmit={createNewLocation}>
<label> locationname </label>
<input type="text" value={locationname} onChange={(e)=>{setLocationname(e.target.value)}}/> <br></br>
<label> latitude </label>
<input type="text" value= {latitude} onChange={(e)=>{setLatitude(e.target.value)}}/> <br></br>
<label> longitude </label>
<input type="text" value= {longitude} onChange={(e)=>{setLongitude(e.target.value)}}/> <br></br>
<button type="submit"> Add a new location </button>
</form>
<p> The current locations </p>
<table>
<tr>
<th> Facility Name </th>
<th> Latitude </th>
<th> Longitude </th>
</tr>
{locations.map(
location =>
(<tr key={location.name}>
<td> {location.locationname} </td>
<td> {location.coordinates.latitude} </td>
<td> {location.coordinates.longitude} </td>
</tr>)
)}
</table>
</div>
)
}
【问题讨论】:
标签: reactjs react-router