bas*_*rd7 7 ruby-on-rails reactjs axios react-on-rails react-hooks
我在带有 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 的项目
Dev*_*eni 10
我假设您在上面定义了这个 useState:
const [coordinated, setCoordinatesFromApi] = useState([])
Run Code Online (Sandbox Code Playgroud)
如果是,那么这就是根本原因:
React.useEffect(() => {
axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [coordinates.length])
Run Code Online (Sandbox Code Playgroud)
通过这样做,您要求 React.useEffect 始终axios.get在coordinates.length更改时调用。这将使这个 useEffect 成为一个无限循环(因为每当 axios 请求完成时,您总是会更改坐标值)。
如果你只想执行一次,你应该只在 useEffect 上传递一个空数组,就像这样
React.useEffect(() => {
axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [])
Run Code Online (Sandbox Code Playgroud)
这样,你axios.get只会被调用一次,你将不再有无限循环
| 归档时间: |
|
| 查看次数: |
2214 次 |
| 最近记录: |