反应:“this”在组件函数中是未定义的

React: "this" is undefined inside a component function

本文关键字:函数 未定义 组件 this 反应      更新时间:2023-09-26
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }
  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
    return (
      <div className="player-controls">
        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />
      </div>
    );
  }
  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }

我想在切换时更新loopActive状态,但处理程序中未定义this对象。根据教程文档,我this应该参考该组件。我错过了什么吗?

ES6 React.Component不会自动将方法绑定到自身。您需要自己将它们绑定在constructor中。喜欢这个:

constructor (props){
  super(props);
  
  this.state = {
      loopActive: false,
      shuffleActive: false,
    };
  
  this.onToggleLoop = this.onToggleLoop.bind(this);
}

有几种方法。

一是添加 this.onToggleLoop = this.onToggleLoop.bind(this);在构造函数中。

另一个是箭头函数 onToggleLoop = (event) => {...} .

然后是onClick={this.onToggleLoop.bind(this)}.

以这种方式编写函数:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}

胖箭头函数

关键字 This 的绑定在胖箭头函数的外部和内部是相同的。这与用函数声明的函数不同,函数可以在调用时将其绑定到另一个对象。维护此绑定对于映射等操作非常方便:this.items.map(x => this.doSomethingWith(x((。

我在渲染函数中遇到了类似的绑定,最终通过以下方式传递了this的上下文:

{someList.map(function(listItem) {
  // your code
}, this)}

我还使用过:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

在我的例子中,这是解决方案 = (( => {}

methodName = (params) => {
//your code here with this.something
}
您应该

注意到this取决于函数的调用方式IE:当函数作为对象的方法调用时,其this设置为调用该方法的对象。

this可以在 JSX 上下文中作为组件对象进行访问,因此您可以将所需的方法作为this方法内联调用。

如果你只是将引用传递给函数/方法,似乎 react 会将其作为独立函数调用。

onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object

如果您使用的是 babel,则使用 ES7 绑定运算符绑定"this"https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding

export default class SignupPage extends React.Component {
  constructor(props) {
    super(props);
  }
  handleSubmit(e) {
    e.preventDefault(); 
    const data = { 
      email: this.refs.email.value,
    } 
  }
  render() {
    const {errors} = this.props;
    return (
      <div className="view-container registrations new">
        <main>
          <form id="sign_up_form" onSubmit={::this.handleSubmit}>
            <div className="field">
              <input ref="email" id="user_email" type="email" placeholder="Email"  />
            </div>
            <div className="field">
              <input ref="password" id="user_password" type="new-password" placeholder="Password"  />
            </div>
            <button type="submit">Sign up</button>
          </form>
        </main>
      </div>
    )
  }
}
我想

解释一下为什么this是未定义的:
如果我们在不是箭头函数的函数中使用this,则this在非严格模式下绑定到全局对象。但是在严格模式下,this将是未定义的(https://www.w3schools.com/js/js_this.asp(。

并且 ES6 模块始终处于严格模式(javascript:在模块内部不需要使用严格(。

您可以使用构造函数中的bind方法将函数onToggleLoop中的thisPlayerControls组件的实例绑定:

constructor(props) {
    super(props)
    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
    this.onToggleLoop = this.onToggleLoop.bind(this)
}

或者改用箭头函数:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}
箭头函数

没有上下文,因此箭头函数中的this将表示定义箭头函数的对象。

如果您在生命周期方法(如 componentDidMount(中调用您创建的方法...那么你只能使用this.onToggleLoop = this.onToogleLoop.bind(this)和胖箭头函数onToggleLoop = (event) => {...}

构造函数中声明函数的正常方法不起作用,因为之前调用了生命周期方法。

就我而言,对于使用 forwardRef 接收 ref 的无状态组件,我必须按照这里所说的去做 https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

从这个(onClick无法访问等效的"this"(

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

对此(它有效(

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()
  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return
      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])
  return targetRef
}
const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)
  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

你可以重写 onToggleLoop 方法是如何从 render(( 方法调用的。

render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
  <div className="player-controls">
    <FontAwesome
      className="player-control-icon"
      name='refresh'
      onClick={(event) => this.onToggleLoop(event)}
      spin={this.state.loopActive}
    />       
  </div>
    );
  }

React 文档显示了从属性中的表达式调用函数的这种模式。

我最近遇到了"这是未定义的"错误 下面的方法对我有用。我将状态传递给我的类构造函数,并且必须简单地将用作箭头函数的函数传递给我的侦听器。

const cartUtils: CartUtils = new CartUtils(cartItems, setCartItems);
onClick={(evt) => cartUtils.getProductInfo(evt)}