我正在尝试实现 useEffect 回调以在卸载组件之前分派操作。此操作的目的是存储组件的最后状态,以便下次加载该组件时可以从该状态恢复。我只希望在卸载时触发此回调。
当尝试为我的 useEffect 使用空依赖项数组时,反应推荐的“eslint-plugin-react-hooks”中的“exhaustive-deps”规则要求我包含我试图保留的值。这会导致每次存储状态时都会触发效果和操作。
有没有比禁用此行的 eslint 更好的方法来处理这种情况?
这就是我想要的:
...
const [value, setValue] = useState('');
useEffect(() => {
return () => {
storeValueAction(value);
};
}, []);
...
Run Code Online (Sandbox Code Playgroud)
eslint-plugin-react-hooks 想要它并导致在每次状态更改时调度操作的方式:
...
const [value, setValue] = useState('');
useEffect(() => {
return () => {
storeValueAction(value);
};
}, [value, storeValueAction]);
...
Run Code Online (Sandbox Code Playgroud)
除了 useEffect 之外,我还应该使用其他东西吗?
在我的react/redux应用程序中,我使用dispatch来调用每次安装组件时从redux中的状态检索数据的操作。问题发生在useState我的方法不起作用
以下是我收到的错误:
React Hook useEffect 缺少依赖项:“dispatch”。包含它或删除依赖项数组。像“getInvoiceData”这样的外部范围值不是有效的依赖项,因为改变它们不会重新渲染组件react-hooks/exhaustive-deps
这是我的代码:
const TableSection = () => {
const invoiceData = useSelector((state => state.tables.invoiceData));
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInvoiceData());
}, [getInvoiceData]);
(...)
export default TableSection;
Run Code Online (Sandbox Code Playgroud) 通过不深入实际用法,我创建了一个简单的示例来解释我想要做什么。
我有一个状态对象{num:0},我想在 10 秒内每秒更新一次 num,据此,我创建了一个工作完美的类组件。
class App extends React.Component {
constructor() {
super();
this.state = {
num: 0
};
}
componentDidMount = () => {
for (let i = 0; i < 10; i++) {
setTimeout(() => this.setState({ num: this.state.num + 1 }), i * 1000);
}
};
render() {
return (
<>
<p>hello</p>
<p>{this.state.num}</p>
</>
);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在功能组件中复制相同的功能,但我做不到。我尝试如下图所示:
const App = () => {
const [state, setState] = React.useState({ num: 0 });
React.useEffect(() => {
for …Run Code Online (Sandbox Code Playgroud) 我正在尝试选择使用 useRef 挂钩选择的 DOM 中另一个元素内部的元素。
const editorRef = useRef(null);
Run Code Online (Sandbox Code Playgroud)
在 useEffect 挂钩内部,我尝试选择 editorRef 上的子元素
useEffect(() => {
editorRef.current.querySelector(".ql-editor").innerHTML = post.content;
}, []);
Run Code Online (Sandbox Code Playgroud)
但我得到一个
类型错误:“无法将属性‘innerHTML’设置为 null”
但是当我在第一次刷新后保存代码时,它实际上起作用并且innerHTML被填充。
我正在尝试每“t”分钟实现一次自动刷新访问令牌;我在 useEffect (在根组件中)中实现了 setInterval,它发送对新访问令牌的请求。当我运行代码时,有时间隔从 onMount 开始,有时根本不运行。
我遇到的另一个问题是,当我将用户重定向到登录页面时,我尝试清除间隔,即使在clearInterval之后它仍然继续运行。
如果有任何其他方法可以按设定的时间间隔实现 JWT 刷新令牌,我也愿意接受。
useEffect(() => {
async function getRefreshToken() {
const response = await axios.post("http://localhost:3001/refreshToken", {refreshToken}, {withCredentials: true})
if (response.data.redirect) {
clearInterval(refresh)
history.replace(`${response.data.redirect}`)
localStorage.clear()
}}
const refresh = setInterval(getRefreshToken, 4000)
}, [])
Run Code Online (Sandbox Code Playgroud) 我在组件内调用 socket.on 函数,但我想在组件卸载时停止它,我正在使用功能组件。
useEffect(() => {
socket.on("new-chat-message", (firstname, lastname, content, date) => {
dispatch(
addMessage({
firstname: firstname,
lastname: lastname,
content: content,
date: date,
})
);
});
}, [dispatch, socket]);
Run Code Online (Sandbox Code Playgroud)
我需要知道如何设置这个useEffect的清理功能。
我有数据试图获取并与下面的代码一起使用,但是当我记录记录的值时,我首先得到一个空数组,然后得到我获取的对象。因此,我无法在我的应用程序中访问该对象的信息。
const [records, setRecords] = useState([]);
useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/record`);
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const records = await response.json();
setRecords(records);
}
getRecords();
return;
}, []);
console.log(records);
Run Code Online (Sandbox Code Playgroud) 我试图从 API 获取一些天气数据,但总是遇到无法读取未定义属性的相同错误。我已经浏览了不同的教程和之前提出的问题,但我无法弄清楚我做错了什么。有人可以帮我一下吗?
export default function Weather(){
const apiKey = process.env.REACT_APP_API_KEY
const weatherUrl = `http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=Saxthorpe&aqi=no`
const [weatherData, setWeatherData] = useState();
const [error, setError] = useState(null);
useEffect(() => {
(
async function(){
try {
const response = await axios.get(weatherUrl);
setWeatherData(response.weatherData);
} catch (error) {
setError(error);
}
}
)();
}, [])
return (
<div className="weather-feature">
<h1>hi</h1>
<p className="location">{weatherData.location.name}</p>
<p className="temp">{weatherData.current.temp_c}</p>
<p className="weather-desc">{weatherData.current.condition.text}</p>
</div>
)
}
Run Code Online (Sandbox Code Playgroud) 有 6 个帖子包含有关用户的信息。如果帖子中的姓名和电子邮件太大,则会被截掉。将鼠标悬停在裁剪的元素上时 - 其旁边会出现一个包含完整信息的块。如果注册成功 - 用户列表已更新 - 最新的列表在开头。我将事件 onMouseOver 和 onMouseOut 放在项目上。是否需要removeEventListener?试图返回 UseEffect 来执行此操作,但所选项目 = null [有当前元素][1]
event-listener addeventlistener reactjs removeeventlistener use-effect
我收到错误“React Hook React.useEffect has a missing dependency: 'openPosts'”,其中 openPosts 是 Hook 中的状态。
export const Posts = (props) => {
const [openPosts, setOpenPosts] = React.useState([]); *openPosts is an array of numbers*
React.useEffect(_ => {
let filteredOpenPosts = openPosts.filter(num => num >= 1);
setOpenPosts(filteredOpenPosts);
}, [props.userId]);
Run Code Online (Sandbox Code Playgroud)
我已经阅读过,但我不明白为什么我会收到这个错误。我可以忽略它吗?
我本质上希望 state 像上面那样过滤并改变,props.userId并认为这将是一种干净的方法。我还可以创建更多状态来跟踪任何更改,props.userId但如果上述方法可行,我更喜欢它。
reactjs ×10
use-effect ×10
javascript ×4
react-hooks ×4
api ×1
asynchronous ×1
next.js ×1
react-redux ×1
redux ×1
setinterval ×1
settimeout ×1
socket.io ×1
use-ref ×1
use-state ×1