更新状态时获取错误(跳过构造函数的状态)

时间:2018-05-05 05:50:44

标签: reactjs

我正在创建一个简单的反应程序,我创建了一个语言数组并将其映射到创建列表项,当用户点击语言列表项时,它应该调用updateLanguage方法并相应地更新状态但是我收到错误。任何人都可以帮我解决问题。

code ::

import React, { Component } from 'react';

class Popular extends React.Component {
   state = {
      selectedLanguage: 'All'
   };

   updateLanguage() {
    this.setState(lang => ({
      selectedLanguage: lang 
    }));
}

   render() {
      const languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python'];
      console.log();

      return (
        <div>
            <ul className = 'languages'>
            <p> Selected Language: {this.state.selectedLanguage} </p>
              {languages.map((lang) => {
               return (
                  <li 
                    onClick={this.updateLanguage} 
                    key={lang}> 
                    {lang}
                  </li>
               )
              })}
            </ul>
          </div>
      );
   }
}

export default Popular;

错误::

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须进行以下更改:

  • 将updateLanguage()绑定到 this (在构造函数中执行此操作)
  • 在构造函数中声明状态

更新以下代码:

import React, { Component } from 'react';

class Popular extends React.Component {
 constructor() {
  super();
  this.state = {
    selectedLanguage: 'All'
  };
  this.updateLanguage = this.updateLanguage.bind(this);
 }

 updateLanguage(lang) {
  this.setState({ selectedLanguage: lang })
 }

 render() {
  let languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python'];
 return (
  <div>
    <ul className = 'languages'>
    <p> Selected Language: {this.state.selectedLanguage} </p>
    {languages.map((lang) => {
       return (
          <li 
             onClick={this.updateLanguage}
             key={lang}> 
             {lang}
          </li>
       )
    })}
    </ul>
 </div>
 );


 }
}

export default Popular;