React - UseState, UseRef..麻烦

React - UseState, UseRef..In Trouble

谁能告诉我怎么了?

我有一个 React 函数组件,其中我在状态变量上使用 '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..

怎么了?有人能帮我吗 ?只是似乎无法理解它...

顺便说一句,我使用完全相同的原理图和另一个状态变量,一切都按预期工作...

你错了。 setNodeslist(prev=>[...prev,n]); 因为你这样做了。 在这里您将获得函数 prev=>[...prev, n] 而不是 [...prev, n]

的数据
const setNodeslist = (data)=>{
  nodeslistRef.current = data;
  _setNodeslist(data)
}

这就是为什么会出现如下错误:

prev=>[...prev,n] but not the DATA..

解决这个问题:试试这个。

const setNodeslist = (callback)=>{
  const newCallback = (prev) => {
    nodeslistRef.current = callback(prev);
    return nodesListRef.current;
  }
  _setNodeslist(newCallback)
}