【问题标题】:React.JS this.state is undefinedReact.JS this.state 未定义
【发布时间】:2015-07-26 11:59:29
【问题描述】:

我目前在 React.JS 中有这个组件,它在一个数组中显示所有传递给它的图像,并且 onMouseOver 它在下面显示一个按钮。我计划使用 setState 检查变量 hover 是真还是假,并相应地切换该图像的按钮,但是我不断收到以下错误:

未捕获的类型错误:无法读取未定义的属性“状态”

var ImageList = React.createClass({
getInitialState: function () {
    return this.state = { hover: false };
},
getComponent: function(index){
      console.log(index);
      if (confirm('Are you sure you want to delete this image?')) {
          // Save it!
      } else {
          // Do nothing!
      }    
},
mouseOver: function () {
    this.setState({hover: true});
    console.log(1);
},

mouseOut: function () {
    this.setState({hover: false});
    console.log(2);
},
render: function() {
var results = this.props.data,
  that = this;
return (
  <ul className="small-block-grid-2 large-block-grid-4">
    {results.map(function(result) {
      return(
              <li key={result.id} onMouseOver={that.mouseOver} onMouseOut={that.mouseOut} ><img className="th" alt="Embedded Image" src={"data:" + result.type + ";"  + "base64," + result.image} /> <button onClick={that.getComponent.bind(that, result.patientproblemimageid)} className={(this.state.hover) ? 'button round button-center btshow' : 'button round button-center bthide'}>Delete Image</button></li>
      )      
    })}
  </ul>
);
}

});

【问题讨论】:

  • 请将代码的基本部分放在问题的正文中。
  • 我只给出了 pastebin 中的基本代码并没有给出完整的代码。
  • 你不明白我的意思。提供代码链接是不好的做法。只需将其嵌入问题中即可。

标签: javascript reactjs


【解决方案1】:

您收到错误是因为您将对 this 的引用存储在您用于引用事件处理程序的 that 变量中,但您没有在三元表达式中使用它来确定 @ 987654324@ 用于 button 元素。

你的代码:

<button
  onClick={ that.getComponent.bind(that, result.patientproblemimageid) } 
  className={ (this.state.hover) ? // this should be that 
    'button round button-center btshow' : 
    'button round button-center bthide'}>Delete Image
</button>

当您将this.state.hover 更改为that.state.hover 时,您不会收到错误消息。

附带说明,您可以简单地将上下文参数传递给map() method,而不是将this 的引用存储在that 变量中。

results.map(function (result) {
  //
}, this);

【讨论】:

    【解决方案2】:

    在 ES5 格式中你不能直接设置 this.state

    var ImageList = React.createClass({
    getInitialState: function () {
     return { hover: false };
    },
    render : function(){
    return(<p>...</p>);
    });
    

    但是,使用新的 ES6 语法,您基本上可以做到这一点:

    class ImageList extends React.Component{
    constructor (props) {
      super(props);
      this.state = {hover : false};
    }
    render (){ ... }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2018-05-09
      • 1970-01-01
      • 2018-01-24
      • 2021-08-06
      相关资源
      最近更新 更多