我试图用来自两个数组的数据渲染一些复选框,这两个数组是一个数组中的id和name以及另一个数组中的count / length。例如:
const count = [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}]]
const type = [{id: "1", name: "iPhone"}, {id: "2",name: "Samsung"}, {id: "3",name: "Huawei"}]
我试图在另一个地图函数中使用一个地图函数。
var text=type.map(function(itm,i){
return [<label key={itm.id}><input type="checkbox" key={itm.id} value={itm.id} name="search"/>{itm.name}</label>, (count && count.length > 0 && count.map( item =>
item.length > 0 && item.map( el =>
Object.keys(el).length > 0 &&
Object.keys(el).map(val => <p>{el[val]}</p>)
)
)[i])];
}).join(' ');
这是应该如何表示。 []是复选框。
[] Iphone (91)
[] samsung (1)
[] huawei (0)
的链接
答案 0 :(得分:1)
您可以遍历count数组,并向array类型添加一个新属性,该属性根据id保存count数组中项目的总数。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
const count = [[{ "1": "91" }], [{ "1": "1" }], [{ "1": "0" }]]
let type = [{ id: "1", name: "iPhone" }, { id: "2", name: "Samsung" }, { id: "3", name: "Huawei" }]
for (let i = 0; i < count.length; i++) {
Object.keys(count[i][0]).forEach(key => {
const index = type.findIndex(x => x.id === key);
const total = parseInt(count[i][0][key], 10);
type[index].total ? type[index].total += total : type[index].total = total;
})
}
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
const check = type.map(item => {
return (
<div>
<input type="checkbox" id="check3"/> {`${item.name} (${item.total ? item.total : 0})`}
</div>
)
})
return (
<div>
{check}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
答案 1 :(得分:1)
您可以通过首先将对象数组的数组简化为简单数组来简化操作
const { count } = this.state;
const itemCount = count && count.length > 0 && count.map(c => c[0]["1"])
然后,当我们执行Array.map()并从itemCount读取时,我们只需获取索引
return (
<div>
{type && type.map((type,i) => (
<label key={type.id}>
<input
type="checkbox"
key={type.id}
value={type.id}
name="search"
onChange={this.handleChange}
onClick={this.handleFilter}/>
{type.name}
({itemCount[i]})
</label>
))}
</div>
)