首页 > 解决方案 > 为什么我的 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 的项目

标签: ruby-on-railsreactjsaxiosreact-hooksreact-on-rails

解决方案


我假设您在上面定义了这个 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只会被调用一次,你将不再有无限循环


推荐阅读