[英]Line 31:7: React Hook useEffect has a missing dependency: 'url'. Either include it or remove the dependency array?
I am having a small issue in my React application where it gives me this warning in the terminal, Line 31:7: React Hook useEffect has a missing dependency: 'url'. Either include it or remove the dependency array.
我在我的 React 应用程序中遇到了一个小问题,它在终端中给了我这个警告,
Line 31:7: React Hook useEffect has a missing dependency: 'url'. Either include it or remove the dependency array.
Line 31:7: React Hook useEffect has a missing dependency: 'url'. Either include it or remove the dependency array.
I have a feeling it has to do with how I made chose to mount the component with useEffect.
我觉得这与我选择使用
useEffect.
but I am not sure anytime I type in the form the console will keep showing the object in does anyone know how I can fix this.但我不确定无论何时我输入表格控制台都会继续显示 object 有人知道我该如何解决这个问题。
Component零件
import React, {useEffect, useState} from 'react'
import axios from 'axios'
const SingleHouse = () => {
const house_id = window.location.href.split('/')[4]
// console.log('HOUSE ID: ', house_id);
//GET HOUSE OBJECT, USESTATE
const url = `http://localhost:5000/api/house-details/${house_id}`
const [mounted, setMounted] = useState(true)
const [house, setHouse] = useState('')
//HANDLE EMAIL FORM, USESTATE
const [email, setEmail] = useState('');
const[subject, setSubject] = useState('');
const [message, setMessage] = useState('')
useEffect(()=>{
const loadData = async () => {
const {data} = await axios.get(url);
if(mounted) {
setHouse(data)
}
}
loadData()
return()=>[setMounted(false)]
},[mounted]);
console.log(house)
const sendMessage = (e) => {
e.preventdefault();
console.log('Email', email);
console.log('Subject', subject);
console.log('message', message)
}
return (
<div className="HosueDescription__container">
{house && ( <div className="HouseDescription__leftContainer">
<img src={house.house_details.house_image} alt=""/>
<h3>{`$${house.house_details.price.toLocaleString(navigator.language, { minimumFractionDigits: 0 })}`}</h3>
<h3>{`${house.house_details.numOfBeds} Bedroom house in ${house.house_location.city} for ${house.house_details.isSaleOrRent}.`}</h3>
<div className="number_container">
<h5> Bedrooms: {house.house_details.numOfBeds}</h5>
<h5> Bathrooms: {house.house_details.numOfBaths}</h5>
<h5> Garages: {house.house_details.numOfGarages}</h5>
<h4>2423 Duck Creek Road</h4>
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi fugiat autem cumque voluptas? Ratione error reprehenderit delectus odio quos iure soluta adipisci fugit, dolores amet neque! Quaerat ipsum laborum consectetur rem voluptas, ullam quisquam aut eligendi nesciunt culpa ad totam, corporis a! Velit consequatur molestias dolor corrupti iure sequi id expedita repellendus impedit neque. Impedit cupiditate laboriosam commodi aperiam nobis odio sunt, error adipisci atque ex minima nisi dignissimos unde! Quod est laudantium, neque dolor atque itaque. Est, dignissimos eum.</h4>
</div>
</div> )}
<div className="HouseForm">
<form className="Form" onSubmit={sendMessage} >
<label>Email</label>
<input type="email" onChange={(e)=>setEmail(e.target.value)} placeholder="Enter a valid email"/>
<label >Subject</label>
<input type="text" onChange={(e)=>setSubject(e.target.value)} placeholder="Enter a Subject"/>
<label >Message</label>
<textarea cols="30" rows="10" onChange={(e)=>setMessage(e.target.value)} placeholder="Enter a message"></textarea>
<button>Send</button>
</form>
</div>
</div>
)
}
export default SingleHouse
Backend Route后端路由
// const express= require('express')
// const router = express.Router()
const router = require('express').Router();
const {House} = require('../../Models/House');
//HOUSE Fetch
router.get('/api/house-sale', async(req, res)=>{
try{
House.find({'house_details.isSaleOrRent': 'SALE'}).exec().then((data)=>{
console.log(data);
return res.status(200).json(data)
})
} catch(error) {
return res.status(500).json({msg: 'server is currently Down :('})
}
})
router.get('/api/house-rent', async(req, res)=>{
try{
House.find({'house_details.isSaleOrRent': 'RENT'}).exec().then((data)=>{
return res.status(200).json(data)
})
} catch(error) {
return res.status(500).json({msg: 'server is currently Down :('})
}
})
router.get('/api/house-details/:id', async(req, res)=>{
await House.findOne({_id:req.params.id}).exec().then(data=>{
return res.status(200).json(data)
}).catch(error =>{
return res.status(400).json(error)
})
})
module.exports = router;
Update dependency array of useEffect
.更新
useEffect
的依赖数组。 React expects all variable/function used in side an useEffect
must be dependency, so that useEffect
take action on update in that dependencies. React 期望
useEffect
中使用的所有变量/函数必须是依赖项,以便useEffect
对该依赖项中的更新采取行动。
useEffect(()=>{
const loadData = async () => {
const {data} = await axios.get(url);
...
}, [mounted, url]);
If particular variable/function is not used outside useEffect
, you can declare within body of the useEffect
.如果特定变量/函数未在
useEffect
之外使用,您可以在useEffect
的主体内声明。
Try to put this line into the useEffect:尝试将此行放入 useEffect 中:
useEffect(()=>{
const url = `http://localhost:5000/api/house-details/${house_id}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.