我对 useEffect 是如何触发的以及它是如何工作的感到有点困惑。我写了一个这样的函数,但 useEffect 根本不运行。我想从API获取数据,然后根据数据渲染页面。但它不会触发 useEffect。如果我不使用 useEffect,它将渲染页面三次。
async function getData() {
var tmpArrData = [];
await fetch("this API is hidden due to the privacy of the company - sorry")
.then((res) => res.json())
.then((data) => {
console.log("data", data);
tmpArrData = data;
});
console.log("tmpData ", tmpArrData);
return tmpArrData;
}
function App() {
const [arrData, setArrData] = useState();
const [loadData, setLoadData] = useState(false);
useEffect(() => {
console.log("if it works, this line should be shown");
const tmpArrData = getData();
setArrData(tmpArrData);
}, [arrData]);
const data …Run Code Online (Sandbox Code Playgroud) 这是对上一个问题的扩展,询问如何防止在按状态更改(排序状态)重新渲染后滚动到顶部
我使用useState和useEffect编写了自动排序表。
我在codesandbox上的代码每3秒从API服务器获取具有2种不同状态(A和B状态)的随机数。
然后按状态标记为表格,排序为AB。
但是,在每次重新渲染时,窗口都会滚动到顶部。
问题是,如何防止滚动到顶部?
在上一个问题中,我尝试了如下所示的useLayoutEffect 。
useEffect(() => {
const updatePosition = () => {
setCurrentScrollY(window.scrollY);
};
window.addEventListener("scroll", updatePosition);
updatePosition();
return () => window.removeEventListener("scroll", updatePosition);
}, []);
useLayoutEffect(() => {
window.scrollTo(0, currentScrollY);
}, [commonKey]);
Run Code Online (Sandbox Code Playgroud)
当我像上面的代码和框代码一样每 3 秒使用REST API请求时,它似乎工作得很好。
但是Websocket会导致连续的状态变化,导致滚动不稳定。
看来Websocket连接正在导致严重的状态变化,从而导致严重的重新渲染。
如何防止重新渲染时滚动到顶部而不出现滚动断断续续的情况?
ps 抱歉我的英语不好。

我想在本机反应中删除事件侦听器,但在反应本机中不推荐使用removeEventListener
return event-listener react-native removeeventlistener use-effect
在这里学习React,我只是想展示一个lottie动画。看起来相当简单,但我在使用 useEffect 挂钩时遇到了一些问题。我使用钩子在页面加载时渲染动画,但它不断重复(有时两次或更多次)。我知道这是因为 useEffect 会多次触发,但我不知道如何处理这个问题。我只想在页面上显示一个动画。我怎样才能实现这个目标?
import React, { useEffect, useRef } from "react";
import "./index.scss";
import lottie from "lottie-web";
const Hero = () => {
const lottieContainer = useRef(null);
useEffect(() => {
lottie.loadAnimation({
container: lottieContainer.current,
renderer: "svg",
loop: true,
autoplay: true,
animationData: require("../../assets/Lottie/developer.json"),
});
}, []);
return (
<div className="hero">
<div ref={lottieContainer}></div>
</div>
);
};
export default Hero;
Run Code Online (Sandbox Code Playgroud) 我想在每次加载页面时随机化一个数组。我正在使用 Nextjs,第一个问题是客户端和服务器不匹配,所以有人建议我需要将随机代码放入 useEffect 挂钩中,但我显然做错了。 ..我需要一些帮助来了解如何修复我的代码。
\nexport default function IndexPage() {\n useEffect(()=>{\n let randomizeArray = [...array].sort(() => 0.5 - Math.random());\n\n let selectedRandomArray = randomizeArray.slice(0, 3);\n },[])\n\n return (\n <div>\n {selectedRandomArray.map((s, id) => (\n <div key={id}>\n <h2>{s.name}</h2>\n </div>\n ))}\n </div>\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n这是 Codesandbox 中没有 useEffect 的示例。它有效,但我\xc2\xb4m在控制台中得到不匹配的客户端/服务器\n https://codesandbox.io/s/shuffle-array-and-return-random-values-in-nextjs-veqy3w?file=/pages/索引.js
\n实际上并不理解为什么此代码部分不能正常工作。该useEffect块在每个滚动位置上重新渲染。另外,我看到这段代码部分:console.log(wrapperRef.current.style.opacity);应该调用 if 和 else if 语句,但事实并非如此。
这是代码:
useEffect(() => {
console.log(wrapperRef.current.style.opacity);
if (wrapperRef.current.style.opacity === 0) {
setIsHidden(true);
console.log("true");
} else if (wrapperRef.current.style.opacity === 1) {
setIsHidden(false);
console.log("false");
}
}, [position]);
Run Code Online (Sandbox Code Playgroud)
我正在尝试App.js从后端将数据加载到我的文件中进行反应。我使用 redux 构建了从后端到前端的整个数据获取和存储管道。这是代码:
function App() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPosts());
}, [dispatch]);
const posts = useSelector((state) => state.posts);
console.log(posts);
return (
<div>
<h1>App</h1>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,每当刷新时console.log,都会在谷歌控制台中显示数据两次。App.js如何让它只运行一次?
我用这段代码得到了一个无限循环。
我一直在尝试其他帖子中的一些解决方案,但它们不起作用。
locationAddress 是一个地址数组,我正在尝试使用 Google Maps Geocode API 获取坐标。
const reducer = (state, action) => {
switch (action.type) {
case 'add':
return [
...state,
{
address: action.address,
name: action.name,
id: action.id
}
];
case 'remove':
return state.filter((_, index) => index !== action.index)
default:
return state;
}
}
const [locationAddress, setLocationAddress] = useReducer(reducer, []);
const [coordinates, setCoordinates] = useState([]);
useEffect(() => {
const fetchLocation = async () => {
for(let i = 0; i < locationAddress.length; i++) {
const response = …Run Code Online (Sandbox Code Playgroud) 我在我的项目中使用蚂蚁设计。我使用 useEffect 从 redux store 获取数据,如下所示;
const settingsRedux = useSelector(state => state.SETTINGS)
Run Code Online (Sandbox Code Playgroud)
之后,我将此数据用于输入的 defaultValue
<Input
defaultValue={settingsRedux.background_image}
onChange={e => dispatch({
type: BACKGROUND_IMAGE,
payload: e.target.value
})}
/>
Run Code Online (Sandbox Code Playgroud)
它实际上有效。但是给出了控制台错误。
Warning: [antd: Form.Item] `defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.
Run Code Online (Sandbox Code Playgroud) 如何在 React 的 useEffect 中为 Axios 调用编写 Jest 测试?
我在这里找到了如何模拟 Axios - /sf/answers/3615829941/
我还知道如何触发 useEffect 如果它是由用户交互(例如单击按钮)调用的。但是在下面的情况下,useEffect 被一个异步函数调用,该函数由 Axios 的响应触发。
例子:
成分
import React, { useState, useEffect } from "react";
import axios from "axios";
const LoadImage = () => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState(null);
const fetchData = async () => {
return await axios
.get("https://picsum.photos/200/300.jpg", {
"Content-Type": "application/xml; charset=utf-8",
})
.then((response) => {
setData(response.config.url);
setLoading(false);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => { …Run Code Online (Sandbox Code Playgroud) use-effect ×10
reactjs ×9
axios ×2
react-hooks ×2
use-state ×2
antd ×1
async-await ×1
fetch ×1
javascript ×1
jestjs ×1
lottie ×1
mern ×1
next.js ×1
random ×1
react-native ×1
redux ×1
return ×1
scroll ×1