javascript - React,调用无状态函数来组织代码,但是这个怎么绑定(bind)呢?

标签 javascript reactjs this bind

鉴于此 react 代码

<form onSubmit={this.onSubmit}>

执行函数

import {onFormSubmit} from '../onFormSubmit'
.....
onSubmit = (e) => {
    // here I have access to "this" thanks to the arrow functions
    e.preventDefault()
    onFormSubmit(this.state.files, this.props)
}

其中 onFormSubmit 作为无状态函数驻留在另一个文件中

export const onFormSubmit = async (files,props) => {
    this.setState(... // error
}

我发现当我在 onFormSubmit 函数中时我丢失了“this”,因此我无法执行 this.setState

那么,我怎样才能保持这个访问权限呢?

选项 A,正如答案中所说,是忘记箭头:

onSubmit = (e) => {
    // here I have access to "this" thanks to the arrow functions
    e.preventDefault()
    onFormSubmit.bind(this)(this.state.files, this.props)
}

.

export async onFormSubmit = function(files,props) {
    this.setState(... // now it works
}

选项 B,将 this 作为变量传递

onSubmit = (e) => {
    // here I have access to "this" thanks to the arrow functions
    e.preventDefault()
    let self = this
    onFormSubmit(self)
}

选项 C,将 onFormSubmit 重新定义为更新程序,如答案中所述,但不是此处的选项,因为该函数不仅更新状态,对于示例:

export const onFormSubmit = async (files,props) => {
    if (files) {
      ... upload file ... parse file ...
      this.setState({'data': data})
    } else {
      ... fetch file ... concat file ... doesn't update the state
    }
    ... and more calculations
    this.setState({...})
}

最佳答案

onFormSubmit 是一个箭头函数,它不能被绑定(bind),除非它被转译为 ES5,并且依赖它会是一个错误。

一个快速而肮脏的修复方法是使其正常运行:

export async function onFormSubmit (files,props) {
    this.setState(...
}

在这种情况下依赖动态 this 可能会很尴尬,此时它并不比将 this 作为参数传递更好。

由于此函数的目的是更新状态,因此更简洁的方法是使其状态为 updater工厂:

export const onFormSubmit = (props) => prevState => {
  const { files } = prevState;
  return { /* new state */ };
}

可以这样使用:

this.setState(onFormSubmit(this.props));

files 可在 prevState 上使用。将 this.statesetState 一起使用是一种反模式,因为 setState 是异步的,这可能会导致竞争条件。

或者如果是异步的,则使其不负责更新状态,例如它返回一个 promise :

const newStateObj = await onFormSubmit(this.state.files, this.props);
this.setState(newStateObj);

如果是同步的,由于上述原因,使用 this.state 并不是一个好主意。

关于javascript - React,调用无状态函数来组织代码,但是这个怎么绑定(bind)呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584947/

相关文章:

reactjs - react 引导自动前缀警告

css - 在带有 sass、css 和语义 ui 的 nextjs 中使用谷歌字体使用react

javascript - 如何根据条件渲染组件?

javascript - 为什么这个 === 窗口在 JavaScript 作用域安全构造函数中是假的?

javascript - 在Javascript中调用匿名函数中的函数时如何使用 "this"关键字?

javascript - 为 material-ui IconButton 设置悬停样式

javascript - 循环嵌套数组

javascript - 为什么 socket.io 不能很好地处理点击事件?

javascript - 让元素的子元素单独但按顺序设置动画

javascript - 如何在函数签名中使用 'this' 关键字来设置默认参数?