📜  如何绑定“this”关键字来解决 React 中的经典错误消息“未定义状态”?

📅  最后修改于: 2022-05-13 01:56:42.464000             🧑  作者: Mango

如何绑定“this”关键字来解决 React 中的经典错误消息“未定义状态”?

JavaScript 中的“this”关键字对于学习者来说总是有些难以理解。基本上,函数中的 this 关键字是通过查看该方法的实际调用方式来确定的。通常在 JavaScript 中,我们使用语法obj.method()调用该方法。在这种情况下,方法函数内的'this'关键字的值是对象'obj'。我们如何调用该方法是'this'经常不可预测的值的根源。

在 React 中,当我们使用事件处理程序时,我们基本上提供了对该事件处理程序的函数引用,当该事件发生时,该函数被调用,这是一个 catch,它在某个时间点而不是立即被调用,当它被调用时,它被调用作为它自己的,现在有任何组件实例对象使用它被调用,这就是为什么方法内的“this”关键字的值是未定义的。为了解决这个问题,我们通常使用 JavaScript 绑定方法绑定 'this' 关键字的值。

错误信息:

示例 1:

index.js:

Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
 
ReactDOM.render(, document.querySelector('#root'))


Javascript
import React, { Component } from 'react'
 
class App extends Component {
  static defaultProps = {
    courseContent : [
      'JSX', 'React Props', 'React State',
      'React Lifecycle Methods',
      'React Event Handlers', 'React Router',
      'React Hooks', 'Readux',
      'React Context'
    ]
  }
   
  constructor(props){
    super(props)
     
    // Set initial state
    this.state = {msg : 'React Course', content:''}
     
    // Binding this keyword of method handleClick
    this.handleClick = this.handleClick.bind(this)
  }
 
  renderContent(){
    return (
      
            {this.props.courseContent.map(content => (           
  • {content}
  •         ))}       
    )   }     handleClick(){         // Changing state     this.setState({       msg : 'Course Content',       content : this.renderContent()     })   }       render(){         // Reference of handleClick, called at some     // point of time on its own gets called like     // handleClick(), thats why this inside     // handleClick is undefined     const button = !this.state.content &&          return (       
        

Message :

             

{this.state.msg}

                   

{this.state.content}

              {button}       
    )   } }   export default App


Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
 
ReactDOM.render(, document.querySelector('#root'))


Javascript
import React from 'react'
import TodoList from './TodoList'
 
const App = () => {
  return 
}
 
export default App


Javascript
import React, { Component } from 'react'
import TodoForm from './TodoForm'
 
class TodoList extends Component{
  constructor(props){
    super(props)
    this.state = { todos : [] }
    // Binding this keyword of method createTodo
    this.createTodo = this.createTodo.bind(this)
    // Binding this keyword of method renderTodo
    this.renderTodos = this.renderTodos.bind(this)
  }
 
  createTodo(todo){
    this.setState({
      todos : [...this.state.todos, todo]
    })
  }
 
 
  renderTodos(){
    const todos = this.state.todos.map(todo => (
      
  •         {todo.task}       
  •     ))     return
      {todos}
      }     render(){     return(       
            

    Todo List

            {this.renderTodos()}                
        )   } }   export default TodoList


    Javascript
    import React, { Component } from 'react'
     
    class TodoForm extends Component{
      constructor(props){
        super(props)
     
        this.state = { task:'' }
         
        // Binding this keyword of method handleChange
        this.handleChange = this.handleChange.bind(this)
         
        // Binding this keyword of method handleSubmit
        this.handleSubmit = this.handleSubmit.bind(this)
      }
     
      handleChange(event){
        this.setState({
          [event.target.name] : event.target.value
        })
      }
     
      handleSubmit(event){
        event.preventDefault()
        this.props.create(this.state)
        this.setState({ task : '' })
      }
     
      render(){
        return(
          
            
                                             
          
        )   } }   export default TodoForm


    应用程序.js:

    Javascript

    import React, { Component } from 'react'
     
    class App extends Component {
      static defaultProps = {
        courseContent : [
          'JSX', 'React Props', 'React State',
          'React Lifecycle Methods',
          'React Event Handlers', 'React Router',
          'React Hooks', 'Readux',
          'React Context'
        ]
      }
       
      constructor(props){
        super(props)
         
        // Set initial state
        this.state = {msg : 'React Course', content:''}
         
        // Binding this keyword of method handleClick
        this.handleClick = this.handleClick.bind(this)
      }
     
      renderContent(){
        return (
          
              {this.props.courseContent.map(content => (           
    • {content}
    •         ))}       
        )   }     handleClick(){         // Changing state     this.setState({       msg : 'Course Content',       content : this.renderContent()     })   }       render(){         // Reference of handleClick, called at some     // point of time on its own gets called like     // handleClick(), thats why this inside     // handleClick is undefined     const button = !this.state.content &&          return (       
            

    Message :

                 

    {this.state.msg}

                       

    {this.state.content}

                  {button}       
        )   } }   export default App

    输出 :

    示例 2:

    index.js:

    Javascript

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
     
    ReactDOM.render(, document.querySelector('#root'))
    

    应用程序.js:

    Javascript

    import React from 'react'
    import TodoList from './TodoList'
     
    const App = () => {
      return 
    }
     
    export default App
    

    TodoList.js:

    Javascript

    import React, { Component } from 'react'
    import TodoForm from './TodoForm'
     
    class TodoList extends Component{
      constructor(props){
        super(props)
        this.state = { todos : [] }
        // Binding this keyword of method createTodo
        this.createTodo = this.createTodo.bind(this)
        // Binding this keyword of method renderTodo
        this.renderTodos = this.renderTodos.bind(this)
      }
     
      createTodo(todo){
        this.setState({
          todos : [...this.state.todos, todo]
        })
      }
     
     
      renderTodos(){
        const todos = this.state.todos.map(todo => (
          
  •         {todo.task}       
  •     ))     return
      {todos}
      }     render(){     return(       
            

    Todo List

            {this.renderTodos()}                
        )   } }   export default TodoList

    TodoForm.js:

    Javascript

    import React, { Component } from 'react'
     
    class TodoForm extends Component{
      constructor(props){
        super(props)
     
        this.state = { task:'' }
         
        // Binding this keyword of method handleChange
        this.handleChange = this.handleChange.bind(this)
         
        // Binding this keyword of method handleSubmit
        this.handleSubmit = this.handleSubmit.bind(this)
      }
     
      handleChange(event){
        this.setState({
          [event.target.name] : event.target.value
        })
      }
     
      handleSubmit(event){
        event.preventDefault()
        this.props.create(this.state)
        this.setState({ task : '' })
      }
     
      render(){
        return(
          
            
                                             
          
        )   } }   export default TodoForm

    输出 :