ReactJS:如何遍历含数组值的字典以渲染组件?
问题诊断与修复方案
嘿,我一眼就瞅出问题出在哪了——你外层的Object.keys(dict).map回调里,压根没返回内层dict[key].map生成的元素数组!React渲染的时候,这外层map相当于没产出任何可渲染的内容,自然就啥都看不到啦。
具体问题拆解
看你这段渲染代码:
{Object.keys(dict).map(function(key, index) { console.log("Arrays:", dict[key]); dict[key].map(function(v, i) { // 这里确实返回了单个元素,但外层map没把这个数组吐出去给React return ( <div> {/* ... 组件代码 ... */} <button data-index={i} onClick={that.removeItem}>Remove </button> </div> ) }) })}
外层的map函数里,你只是跑了一遍内层的dict[key].map,但没把它的返回值(也就是每个数组对应的元素列表)返回给外层。React要求每个map回调都得返回要渲染的节点,不然直接忽略这部分内容。
修复方案(超简单)
只需要在外层map里,把内层map的结果return出去就行,另外还有俩小细节可以优化下:
- 给每个最外层的元素加个唯一的
key(用字典的key参数比用index靠谱,避免排序变化导致的问题) - 内层的key最好结合外层的key和内层的i,防止不同数组里的i重复造成key冲突
修复后的代码:
{Object.keys(dict).map(function(key, index) { console.log("Arrays:", dict[key]); // 关键:把内层map的结果return出去! return dict[key].map(function(v, i) { // 组合出全局唯一的key const uniqueKey = `${key}-${i}`; return ( <div key={uniqueKey}> {(that.props.hashNode.get().constructor.name === "Parent") ? <ParentComponent name={`${that.props.name}${uniqueKey}`} key={uniqueKey} timer={that.props.timer} callback={that.childChange} values={v} newParent={that.props.hashNode.get()} /> : <NodeComponent name={`${that.props.name}${uniqueKey}`} key={uniqueKey} timer={that.props.timer} callback={that.childChange} value={v} newNode={that.props.hashNode.get()} /> } <button data-index={uniqueKey} onClick={that.removeItem}>Remove </button> </div> ) }) })}
额外需要检查的点
- 确认
this.state.values和你传入的props.values是一致的!如果组件里没把props同步到state,那this.state.values可能是空的哦~ 可以在构造函数或者componentDidMount里把props赋值过去:
constructor(props) { super(props); this.state = { values: props.values }; }
- 检查
that.childChange和that.removeItem有没有正确绑定this,不然点击事件可能没反应——最好在构造函数里绑定:
constructor(props) { super(props); this.state = { values: props.values }; this.childChange = this.childChange.bind(this); this.removeItem = this.removeItem.bind(this); this.addEmptyItem = this.addEmptyItem.bind(this); }
这样改完之后,应该就能正常渲染所有数组里的元素啦!
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

