【发布时间】:2020-04-13 16:41:52
【问题描述】:
我有一个对象数组,并在输入中渲染其中的每个项目,在本节下,我有一个按钮可以做某事
我想检查每个“输入”项,如果它是空的,不要调用按钮上按下的函数
我的代码不适用于第一个对象,
状态
toolsUsed: [
{
id: 0,
name: '..',
price: '..',
count: '..',
},
{
id: 1,
name: '..',
price: '..',
count: '..',
},
...
],
]
这是我的可迭代数组
renderToolsUsed = () => {
const {toolsUsed} = this.state;
return toolsUsed.map(({name, id, price, count}, i) => {
console.log('i', i);
if (
toolsUsed[i].name.length > 0 &&
toolsUsed[i].price.length > 0 &&
toolsUsed[i].count.length > 0
) {
this.setState({valid: true});
}
return(
<View>.....</View>
)
}
按钮功能
pressed = ()=>{
if(this.state.vaild){
call...
}else{
alert("please fill all fields");
}
}
编辑
回答@SLePort
renderToolsUsed = () => {
const {toolsUsed} = this.state;
return toolsUsed.map((item, i) => {
console.log(item);
this.setState(
{
// ...item,
isValid: ['name', 'price', 'count'].every(
key => item[key].length > 0,
),
},
() => console.log('isValid', this.state.isValid),
);
return (
<View key={i} style={styles.tools}>
<Text>{item.name}</Text>
...
</View>
);
});
};
【问题讨论】:
标签: javascript arrays reactjs loops