为什么我们不能在转换函数中获得状态

问题描述

react-admin 中,我想在提交之前更改表单,从状态添加变量。但是变量的值仍然是初始值,我无法将其设置为实际值。下面有一个代码片段。我怎样才能实现我的目标?

const MyComponent = props => {
    // setSomeVariable will be called elsewhere,so the value of someVariable will be changed
    const [someVariable,setSomeVariable] = useState('initial')

    const transform = data => {
        data['someVariable'] = someVariable  //it's value will remain 'initial'. How to set actual value?
        return data
    }

    return <Create {...props} transform={transform}>
           ...
           </Create>
}

在这些问题中有类似的行为,但没有得到回答:

Trying to use react-admin transform function on <Create />

React Admin: how to pass state to transform

谢谢。

解决方法

使用 setSomeVariable 更新状态

const MyComponent = props => {
  // setVariable will be called elsewhere,so the value of someVariable will be changed
  const [someVariable,setSomeVariable] = useState('initial')

  const transform = data => {
    const newSomeVariable  = data['someVariable'] //it's value will remain 'initial'. How to set actual value?
    setSomeVariable(newSomeVariable);
    return data
  }

  return <Create {...props} transform={transform}>
    ...
           </Create>
}