微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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>
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。