我正在处理一些代码,但遇到了这个错误。我之前没有在其他项目中看到它出现过,所以我不确定它为什么会出现在这里。我正在使用 useEffect 钩子,我想在用户从下拉列表中选择一个选项时更新它。发生的情况是,当用户选择一个选项时,我收到以下错误TypeError: Assignment to constant variable.。我知道这是说我正在尝试更新一个不可能发生的常量,但我不明白为什么。不幸的是,
我无法确定如何正确呈现我的代码,但接下来的两行是我遇到问题的代码行。然后是我正在处理的完整代码。
const [TitleId, setTitleId] = useState(0); const TitleSelect = event =>{
console.log(event.target.value);
setTitleId=(32);
};
import React, {useState,useEffect} from 'react';
// import '../app.css';
const Header = props=> {
const [TitleList, setTitleList] = useState([]);
const [TitleId, setTitleId] = useState(0);
useEffect(()=>{
console.log('first start');
setTitleList(
props.data.map((title,index)=>({
title: title.title,
id: index
}))
)
},[])
const TitleSelect = event =>{
console.log(event.target.value);
setTitleId=(32);
};
let content = (
<select
onChange={TitleSelect}>
{TitleList.map(title=>(
<option key={title.id} value={title.id}>
{title.title}
</option>
))}
</select>) …Run Code Online (Sandbox Code Playgroud) 所以我有这段代码不能按预期工作。当前焦点是在父组件上使用 useState() 设置的,因此它是一个状态变量。但是,当父级中的 currentFocus 值发生变化时,这里的焦点变量本身不会更新。我本来希望重新渲染父组件,而重新渲染该组件会导致 foucs 值发生变化。
import React, { useRef, useEffect, useState } from 'react';
const CookieDetails = props => {
const {
name,
cost,
value,
numOwned,
onMouseClick,
cookieId,
currentFocus,
} = props;
let cookieInfoRef = useRef(null);
//My focus doesnt change even if I change currentFocus in parent component
const [focus, setFocus] = useState(currentFocus);
useEffect(() => {
console.log('currentFocus', currentFocus);
console.log('focus', focus);
console.log('cookieID', cookieId);
if (cookieInfoRef.current && cookieId === focus) {
console.log('current', cookieInfoRef.current);
cookieInfoRef.current.focus();
}
}, [focus]);
return (
<React.Fragment> …Run Code Online (Sandbox Code Playgroud) 我从来没有找到解决我的 useEffect 问题的方法:我正在使用 firebase 并在我的数据库上创建一个监听器(onSnapshot)来获取我的对象“Player”的最后状态,当状态currentGroup和currentUser可用时我可以获得
const [currentGroup, setCurrentGroup] = useState(null)
const [currentUser, setCurrentUser] = useState(null)
const [currentPlayer, setCurrentPlayer] = useState(null)
const IDefineMyListener = () =>{
return firebase.doc(`group/${currentGroup.id}${users/${currentUser.id}/`)
.onSnpashot(snap =>{
//I get my snap because it changed
setCurrentPlayer(snap.data())
})
}
Run Code Online (Sandbox Code Playgroud)
currentGroup正如上面,当和可用时,我调用 useEffect currentUser,并且(重要)如果我还没有设置currentPlayer
useEffect(() => {
if (!currentGroup || !currentUser) return
if (!currentPlayer) {
let unsubscribe = IDefineMyListener()
return (() => {
unsubscribe()
})
}
},[currentGroup,currentUser])
Run Code Online (Sandbox Code Playgroud)
正如您所想, unsubscribe()即使IDefineMyListener()没有重新定义,也会被调用。换句话说,当currentGroup或currentUser …
firebase reactjs google-cloud-firestore react-hooks use-effect
为什么会fetchData多次触发?在console.log似乎环几乎是无限?如何让它在加载时仅运行一次并在fetchData()稍后调用时仅触发一次?我在这里做错了什么或错过了什么?
const [data, setData] = useState(null);
let fetchData = React.useCallback(async () => {
const result = await fetch(`api/data/get`);
const body = await result.json();
setData(body);
console.log(data)
},[data])
useEffect(() => {
fetchData();
},[fetchData]);
Run Code Online (Sandbox Code Playgroud)
更新(附加问题):如何在下面data的之前等待填充return()现在给出错误,因为它最初为空?:data.map is not a function
return (
<select>
{data.map((value, index) => {
return <option key={index}>{value}</option>
})}
</select>
)
Run Code Online (Sandbox Code Playgroud) 我目前正在尝试弄清楚如何在将应用程序包装在 Context 提供程序中(从 useReducer 获取值)然后通过带有 useEffect 挂钩的子组件进行更新时避免创建无限循环。
CodeSandbox 上有一个问题示例。
显然,如果不在这里重新发布所有代码,就很难谈论这个问题,但关键点是:
根:
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return (
<Context.Provider value={value}>
...
</Context.Provider>
Run Code Online (Sandbox Code Playgroud)
孩子:
export const Page1: FC = () => {
const { dispatch, state } = useContext(Context);
const { isLoading } = state;
useEffect(() => {
dispatch({
type: "loading",
payload: false
});
}, [dispatch]);
return (...)
Run Code Online (Sandbox Code Playgroud)
我可能遗漏了一些明显的东西,但任何指针都可能会帮助遇到同样问题的其他人。
我需要使用 d3 从 csv 文件中读取并将结果存储在状态变量中。我在 useEffect Hook 中分离了初始化,但是当我尝试在返回 null 后使用状态变量时:
const ItalyMapRegion = ({ w, h, onChangeRegion }) => {
const [zone, setZone] = useState(null);
useEffect(() => {
console.log("once");
d3.csv(data).then(function (data) {
setZone(data);
});
}, []);
useEffect(() => {
console.log(zone); //this return null, why?
......
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我有从 redux 中提取的事件,如果events数组包含数据,updateData则将用于将事件过滤到状态 var 中data。
我已经data和events都添加到了这里提到的依赖数组中。但我仍然收到此错误:
const SingleTable = () => {
const events = useSelector(state => eventsSelector(state));
const [data, updateData] = useState([]);
const [sortCol, updateSortCol] = useState(0);
const [sortDir, updateSortDir] = useState('ascending');
useEffect(() => {
const formattedArray = events ? formatLoss(events): [];
events && updateData(formattedArray);
}, [data, events]);
//...
Run Code Online (Sandbox Code Playgroud)
想法,想法?
我正在关注 YouTube 教程,该教程使用 React 17,而我正在使用 React 18。我所在的部分是我们正在格式化一些动画文本,一切正常,但我所在的部分将句子的字母设置为在悬停时更改。我收到以下错误:
react-dom.development.js:86 警告:useEffect 不得返回除用于清理的函数之外的任何内容。您返回:2
这是给我带来问题的代码片段:
useEffect(() => {
return setTimeout(() => {
setLetterClass('text-animate-hover')
}, 4000)
}, [])
Run Code Online (Sandbox Code Playgroud)
这是我的 text-animate-hover 类的 scss:
.text-animate-hover {
min-width: 10px;
display: inline-block;
animation-fill-mode: both;
&:hover {
animation: rubberBand 1s;
color: #ffd700;
}
}
Run Code Online (Sandbox Code Playgroud)
我读到我不需要在 React 18 中使用“useEffect”,但我不明白我应该做什么。我所做的大部分搜索都返回了很多使用“useEffect”和“异步”问题的实例,我在将这些实例与我的特定问题联系起来时遇到了麻烦。
我很感激任何帮助。
-N8
我已经创建了一个 React 应用程序。对于数据获取,我使用了 axios。我的应用程序按预期工作正常。但是在我的终端中,我收到了这样的警告Line 34:6: React Hook useEffect has a missing dependency: 'props.match.params.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps。我不想使用// eslint-disable-next-line react-hooks/exhaustive-deps. 有什么替代解决方案吗?
useEffect(() => {
axios
.get("http://localhost:5000/students/" + props.match.params.id)
.then(response => {
setState({
name: response.data.name,
birthday: response.data.birthday,
address: response.data.address,
zipcode: response.data.zipcode,
city: response.data.city,
phone: response.data.phone,
email: response.data.email
});
})
.catch(function(error) {
console.log(error);
});
}, []);
Run Code Online (Sandbox Code Playgroud) use-effect ×9
reactjs ×8
react-hooks ×6
javascript ×4
use-state ×3
axios ×1
csv ×1
d3.js ×1
fetch-api ×1
firebase ×1
sass ×1
use-context ×1
use-reducer ×1