React.Children.map中无法访问this.state问题求助
问题原因与解决方案
嘿,这个问题其实很好排查——你错误地把state定义成静态属性了!
为什么会报错?
React类组件的state是属于组件实例的,而你写的static state是挂载在类本身的属性,并不是每个组件实例的state。当你的render函数执行时,组件实例的this.state根本没有被初始化,自然就是null/undefined,所以才会抛出TypeError: Cannot read property 'inputDevices' of null的错误。
怎么修复?
你有两种简单的修复方式,选一种适合你的就行:
方式1:使用类实例字段(推荐,如果你用的是支持ES6+ class fields的环境)
直接去掉static关键字,让state成为组件实例的属性:
state = { inputDevices: [ { id: 'test', name: 'test' }, { id: 'test1', name: 'test1' } ], outputDevices: [ { id: 'test', name: 'test' }, { id: 'test1', name: 'test1' } ] }
方式2:在constructor中初始化state
这是React类组件的传统初始化方式,兼容性更好:
constructor(props) { super(props); this.state = { inputDevices: [ { id: 'test', name: 'test' }, { id: 'test1', name: 'test1' } ], outputDevices: [ { id: 'test', name: 'test' }, { id: 'test1', name: 'test1' } ] }; }
额外提醒
如果你确实需要一些静态的默认数据,可以给它起个别的名字(比如static defaultDeviceList),然后在初始化实例state的时候引用它,但你的场景是要把设备数据传递给子组件,后续大概率还要更新这些数据,所以必须用实例的state,不能用静态属性哦。
内容的提问来源于stack exchange,提问作者BugHunterUK
相关产品推荐
相关产品推荐

