如何在回调函数中传递最新状态变量对于React函数组件

问题描述

嗨!

我目前正在尝试优化我们的App并将其转换为主要功能组件,但是对于这一特定组件,我感到很困惑,好像我缺少类组件的功能(或一种理解)!

...more code above(cycleRole,etc...)...

function Creator({ wall }) {
  const [arr,setArr] = useState([]);
  const [state,setState] = useState({
    start: 0,end: 0,regular: 0,foot: 0,total: 0,});

  // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  // This is the function that I need to pass as a mouseDown listener
  // I want it to have access to the latest state values of (arr,state)
  const update = (event) => {
    const id = parseInt(event.target.getAttribute('id'),10);
    const newState = cycleRole(arr[id],state); // returns a new state object
    arr[id].role = newState.hold; // mutates the array (but I will use array spread to create a new array)
    Object.keys(holdRoles).map((key) => {
      if (holdRoles[key].id === arr[id].role) {
        event.target.setAttribute('class',`${holdRoles[key].className}`);
      }
    });
  // these setstate calls work(new values in the render)
  // but their values are never updated inside this function
    setArr([...arr]);
    setState({ ...newState });
  };
  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  // This function initialises my component and sets the mousedown listeners
  useEffect(() => {
    const svg = document.getElementById(`${wall.name}Svg`);
    const paths = Array.from(svg.getElementsByTagName('path'));
    const arrTmp = paths.map((path,index) => {
      path.setAttribute('id',index);
      path.addEventListener('mousedown',update);
      return {
        id: `holdID${index}`,role: holdRoles.inactive.id,};
    });
    setArr(arrTmp);
  },[wall]);

  return (
    <>
      <div
        id="Creator"
        dangerouslySetInnerHTML={{ __html: svg }}
      />
    </>
  );
}

const mapStatetoProps = (state) => ({
  wall: state.wall.data,});

export default connect(mapStatetoProps,null)(Creator);

我怀疑JS复制了函数中定义的变量,而这些正是回调将始终使用的变量,但是我看不到如何在功能组件中实现解决方案。

在Class组件中,我将回调设置为类函数,并仅从回调中的类状态获取状态变量,例如:


class Example extends React.component {
  constructor() {
    const state = {
      stateItem: 0,};

    this.updateMystate = this.updateMystate.bind(this);
  }

  updateMystate(event) {
    const { stateItem } = this.state;
    this.setState({ stateItem: stateItem + 1 });
  }

  render() {
    return <div onClick={this.updateMystate}>foobarbaz</div>;
  }
}



我尝试使用useRef和useCallback均无济于事,但我不知道自己是否尝试正确。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)