【发布时间】:2021-05-29 02:46:00
【问题描述】:
谁能告诉我怎么了?
我有一个反应函数组件,我在这样的状态变量上使用“useState”和“UseRef”......
**A**. `const [nodeslist,_setNodeslist] = useState([]);`
**B**. `const nodeslistRef = useRef(nodeslist);`
**C**.`const setNodeslist = (data)=>{
nodeslistRef.current = data;
_setNodeslist(data)
}`
**D**. somewhere ..on an event which adds nodes...
`
let n = {id:'someid',attrs:{name:'somename',descr:'somedescr'}};
setNodeslist(prev=>[...prev,n]);
`
**E**. in another event handler...click.. I am trtying to find the node clicked..but I cant
iterate the 'nodeslist' with ref like so..
`nodeslistRef.current.forEach((item,i)=>{
.....
});`
***GIVES ERROR nodeslistRef.current.forEach is NOT A FUNCTION..***
a. `console.log(nodeslistRef.current)` shows -> prev=>[...prev,n] but not the DATA..
b. `JSON.stringify(nodeslist)` on page shows expected data..and seems to updating as soon as
a node is added to the page..
那么有什么问题吗?有人能帮我吗 ?只是似乎无法让我的头缠住它......
顺便说一句,我正在使用完全相同的原理图和另一个状态变量,并且一切都按预期工作......
【问题讨论】:
标签: reactjs react-hooks use-state use-ref