我有一个子组件,它通过事件向父组件发出操作:
子组件:
export default function ChildComponent(props) {
const classes = useStyles();
const [value, setValue] = React.useState([0, 5]);
const handleChange = (_, newValue) => {
setValue(newValue);
props.updateData(newValue)
};
return (
<div className={classes.root}>
<GrandSonComponent
value={value}
onChange={handleChange}
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
父组件:
export const ParentComponent = () => {
const [loading, setLoading] = React.useState(true);
const { appData, appDispatch } = React.useContext(Context);
function fetchElements(val) {
fetchData(val);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => { return fetchData() }, []);
async function fetchData(params) {
const res = …Run Code Online (Sandbox Code Playgroud) 在使用 React hooks 开发 Swiper 组件时,我通常使用 getBoundingClientRect().width,但在某些示例中 getBoundingClientRect().width 返回 0。
useEffect(() => {
const width = containerWrap.current.getBoundingClientRect().width;
console.log(containerWrap.current.getBoundingClientRect().width) // 0
console.log(document.body.getBoundingClientRect().width); // 750
// it works well
// setTimeout(() => {
// console.log(containerWrap.current.getBoundingClientRect().width) // 750
// }, 0)
setSwiperWidth(width);
if (selectedIndex >= count) {
active.current = 0;
}
setSwipeStyle({...swipeStyle, transform: `translate3d(-${width * (selectedIndex >= count ? 1 : (selectedIndex + 1))}px, 0, 0)`, width: ((count + 2) * width) + 'px'})
return () => {
containerWrap.current.remove();
}
}, [])
Run Code Online (Sandbox Code Playgroud)
我在useEffect函数中使用setTimeout,效果很好; …
我尝试使用 useEffect() 和 setInterval() 每 3 秒更改一次文本。现在它只更改文本一次,然后就不再更改了。我究竟做错了什么?
编辑:我正在使用库“react-spring”
const [toggle, setToggle] = useState(false)
useEffect(() => {
setInterval(() => {
switch (toggle) {
case false: setToggle(true)
break;
case true: setToggle(false)
break;
}
}, 3000);
}, [])
{transitions.map(({ item, props }) => item
? <animated.div style={props}>Text that changes #1</animated.div>
: <animated.div style={props}>Text that changes #2</animated.div>)}
Run Code Online (Sandbox Code Playgroud) 我在 SO 上看到过这个问题,但我似乎无法弄清楚它为什么存在。
我从这里开始学习教程
我正在使用 useState 但当我尝试更新状态时,数组为空。我正在使用状态最初创建一个空数组。在收到消息时,我尝试使用扩展运算符将消息添加到数组中,我已经无数次使用它来将对象添加到数组中(但从未在 useEffect 中使用)。
如果我取消注释行的注释,“聊天”将按其应有的方式更新,但我无法理解为什么扩展运算符不起作用,我需要使用 useRef 来使其工作。我不想为每个相应的 useState 提供大量的 useRef (至少不知道为什么有必要)
任何人都可以看到我做错了什么,或者解释为什么我需要 useRef 吗?
const [chat, setChat ] = useState([]);
//const latestChat = useRef(null);
//latestChat.current = chat;
// ...
useEffect(() => {
if (connection) {
connection.start()
.then(result => {
console.log('Connected!');
connection.on('ReceiveMessage', message => {
const newMsg = {
user: message.user,
message:message.message
}
setChat([...chat, newMsg]); // issue with this line. chat is always empty
//const updatedChat = [...latestChat.current];
//updatedChat.push(message);
//setChat(updatedChat);
});
})
.catch(e => console.log('Connection …Run Code Online (Sandbox Code Playgroud) 再会。这是检查 AuthContext 的本地存储中是否已有令牌的最佳方法吗?我使用 useEffect 挂钩来检查令牌是否已存在。我是否应该更改 isAuthenticated 的初始状态,因为它在渲染时始终为 false?我不知道。谢谢
import React, { useState, useContext, useEffect } from "react";
const AuthContext = React.createContext();
export function useAuth() {
return useContext(AuthContext);
}
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setAuthenticated] = useState(false);
const login = () => {
setAuthenticated(true);
};
useEffect(() => {
const token = localStorage.getItem("AuthToken");
if (token) {
setAuthenticated(true);
} else if (token === null) {
setAuthenticated(false);
}
return () => {};
}, []);
return <AuthContext.Provider value={{ isAuthenticated, …Run Code Online (Sandbox Code Playgroud) authentication local-storage reactjs react-context use-effect
我正在尝试制作需要字母成绩和学分来计算 GPA 的 GPA 计算器。字母等级有助于找到分数,例如 A+ 表示 4.00 或 D 表示 1.00。
问题是,当我多次更改成绩值时,我会收到此错误,并且我的错误行始终处于 handlePoints()功能状态。确切的行是
const newPoints = [...points];
newPoints[i] = 4;
setPoints(...newPoints);
Run Code Online (Sandbox Code Playgroud)
下面是我所有的代码
import React, { useEffect, useState } from "react";
import SgpaComponent from "./SgpaComponent";
function Sgpa() {
const [subjects, setSubjects] = useState(["Subject Name"]);
const [grades, setGrades] = useState(["A+"]);
const [points, setPoints] = useState([4]);
const [credits, setCredits] = useState([3]);
const [sgpa, setSgpa] = useState();
function handleAdd() {
setSubjects((prev) => [...prev, "Subject Name"]);
setGrades((prev) => [...prev, "A+"]);
setPoints((prev) => [...prev, …Run Code Online (Sandbox Code Playgroud) unsubscribe如您所知,在 useEffect 中,如果我们将任何侦听器分配给 const,我们会在最后返回 ,unsubscribe如下所示
当我们使用
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
return unsubscribe;
}, [navigation]);
Run Code Online (Sandbox Code Playgroud)
如我所愿
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// code
})
const unsubscribe2 = navigation.addListener('blur', () => {
// code
})
// need to return both listeners
}, [navigation]);
Run Code Online (Sandbox Code Playgroud) 我正在使用"react-router": "^6.0.0-beta.0"并且在我的Activate.js 文件中,我在 Chrome 上不断收到错误,如下所示
类型错误:无法读取未定义的属性“params”
这是我的 Activate.js 的代码示例,我正在使用带有React hooks的功能组件,现在该代码的工作原理是,当您注册并单击电子邮件激活链接时向您发送电子邮件时,它会将您重定向到单击一个按钮以便激活帐户,这正是我得到“无法读取未定义的属性‘参数’”的地方 下面的代码正是我得到错误的地方。
useEffect(() => {
/* get token from params like /active/token
then decode this token and get name*/
let token = match.params.token; //Error is occuring Here
let name = jwt.decode(token);
if (token) {
setFormData({ ...formData, name, token });
}
Run Code Online (Sandbox Code Playgroud)
整个Activate.js文件的完整代码示例如下
/* eslint-disable no-unused-vars */
import React, { useState, useEffect } from 'react';
import authSvg from '../assets/welcome.svg';
import { …Run Code Online (Sandbox Code Playgroud) 我试图在 React 中使用 useEffect 钩子来仅触发某些函数一次。我知道这通常可以通过以下方式完成
useEffect(() => {
// some functions
}
}, [])
Run Code Online (Sandbox Code Playgroud)
但是,这些函数需要加载一些值。所以,我只希望这个 useEffect 在值不为空时仅触发一次。
useEffect(() => {
// some functions
}, [theValue])
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的,但我知道每当发生变化时都会触发它theValue。
如何将 useEffect 更改为在theValue不为空时仅运行一次?
useEffect这段代码每次窗口大小改变时都会运行,但是第二个参数useEffect是一个空数组,我想只要第二个参数与上次相比没有改变,就useEffect不会运行
import React from "react"
export default function WindowTracker() {
const [windowWidth, setWindowWidth] = React.useState(window.innerWidth)
React.useEffect(() => {
window.addEventListener("resize", function() {
setWindowWidth(window.innerWidth)
})
}, [])
return (
<h1>Window width: {windowWidth}</h1>
)
}Run Code Online (Sandbox Code Playgroud)
use-effect ×10
reactjs ×9
react-hooks ×6
javascript ×5
mern ×1
node.js ×1
react-native ×1
use-state ×1