You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件动态展示对象所有属性报错的解决咨询

解决React类组件中Cannot read property 'state' of undefined的问题

嗨,这个问题其实挺常见的,就是函数里的this指向出问题啦!你在map里用了普通的function作为回调,这个函数内部的this并没有指向你的组件实例,所以自然找不到this.state。给你几个简单的解决办法:

方法一:改用箭头函数

箭头函数会自动继承外层作用域的this(也就是你的组件实例),直接替换就行:

{ Object.keys(this.state.freightRelayPrice).map((key) => {
  return <td className="whiteSpaceNoWrap">{ this.state.freightRelayPrice[key] }</td>
}) }

方法二:给map传入第二个参数绑定this

Array.map()方法允许你传入第二个参数,作为回调函数执行时的this值,直接把组件的this传进去就好:

{ Object.keys(this.state.freightRelayPrice).map(function(key) {
  return <td className="whiteSpaceNoWrap">{ this.state.freightRelayPrice[key] }</td>
}, this) }

方法三:提前解构state里的变量

把freightRelayPrice从state里解构出来,这样就不用在回调里依赖this了,代码也更简洁:

render() {
  const Fragment = React.Fragment;
  const { freightRelayPrice } = this.state;
  return (
    <Fragment>
      <tr>
        { Object.keys(freightRelayPrice).map(key => (
          <td className="whiteSpaceNoWrap">{ freightRelayPrice[key] }</td>
        )) }
      </tr>
    </Fragment>
  )
}

为什么会出现这个错误?

普通函数在被调用时,this的指向由调用它的上下文决定。在React的严格模式下,Array.map()调用回调时默认的this是undefined,所以你在回调里访问this.state就会报错。而箭头函数没有自己的this,会沿用外层(也就是组件render方法)的this,所以就能正常访问组件的state了。

内容的提问来源于stack exchange,提问作者dns_nx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:36