【问题标题】:React - UseState, UseRef..In TroubleReact - UseState,UseRef..In Trouble
【发布时间】: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


    【解决方案1】:

    你错了。 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)
    }
    

    【讨论】:

    • 这行得通……但是,您如何正确解释相同的原理图,以便在另一个状态变量上按预期正确执行所有操作? @张天宇
    • 我猜这不完全一样。这是处理问题的正确方法
    猜你喜欢
    • 2020-11-23
    • 2021-03-01
    • 2020-02-17
    • 2020-06-20
    • 2019-10-20
    • 2021-03-12
    • 2022-12-02
    • 2021-04-01
    • 2022-12-01
    相关资源
    最近更新 更多