ruby-on-rails - 为什么我的 axios 使用 React.useEffect 一遍又一遍地从 Rails 后端获取调用?
问题描述
我在带有 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])
这成功地填充了地图,但意味着我不能使用onClick's
功能(因为我认为堆栈被这个请求置顶?)
我在 Rails 中的 CoordinatesController 上的索引方法:
def index
coordinates = Coordinate.all
render json: CoordinateSerializer.new(coordinates).serialized_json
end
注意:这是我第一个将 React 链接到 Rails 以及使用 Hooks 的项目
解决方案
我假设您在上面定义了这个 useState:
const [coordinated, setCoordinatesFromApi] = useState([])
如果是,那么这就是根本原因:
React.useEffect(() => {
axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [coordinates.length])
通过这样做,您要求 React.useEffect 在更改时始终axios.get
调用coordinates.length
。这将使这个 useEffect 成为一个无限循环(因为每当 axios 请求完成时,您总是会更改坐标值)。
如果你只想执行一次,你应该在 useEffect 上传递一个空数组,像这样
React.useEffect(() => {
axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [])
这样,你axios.get
只会被调用一次,你将不再有无限循环
推荐阅读
- android - 片段无故失去对活动的引用
- python - Pandas 中的 Excel 查询自动化
- javascript - 使用 phantomJS 抓取 javascript 网页
- python-3.x - AttributeError:“str”对象没有属性“ndim”,无法使用 model.predict()
- firebase - Firebase 托管引发错误:Uncaught SyntaxError: Unexpected identifier
- sql-server - SSRS 数据驱动订阅
- node.js - 如何清理节点/npm snd 重新启动。节点gyp错误
- unificationengine - 如何使用统一引擎向 Line 发送消息?
- c# - Automapper map propeprties to list
- asp.net - how to give xml file source in app.config and write/read those xml files form winform?