我在带有 Hooks 前端的 React 上使用 axios 来发出获取请求,以使用 Rails 后端中的种子数据填充我的 react-google-maps/api GoogleMaps Marker 组件。当我让 rails 服务器运行时,服务器会反复进行此调用。
以下行导致在axios.get循环中调用 :
React.useEffect(() => {
// Get Coordinates from api
// Update Coordinates in state
axios.get('/api/v1/coordinates.json')
.then(response => response.data.data.map(coord =>
setCoordinateFromApi(coord.attributes)))
.catch(error => console.log(error))
}, [coordinates.length])
Run Code Online (Sandbox Code Playgroud)
这成功地填充了地图,但意味着我不能使用 ```onClick`s`` 功能(因为我认为这个请求正在堆栈顶部?)
我在 Rails 中的 CoordinatesController 上的索引方法:
def index
coordinates = Coordinate.all
render json: CoordinateSerializer.new(coordinates).serialized_json
end
Run Code Online (Sandbox Code Playgroud)
注意:这是我第一个将 React 链接到 Rails 以及使用 Hooks 的项目