本文介绍了如何检查数组中的每个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,并在输入中呈现其中的每个项目,在此部分下,我有一个执行某些操作的按钮

I have an array of objects and render every item inside it in input and under this section, I have a button that does something

我要检查每个输入"项是否为空,不要调用按钮上按下的功能

I want to check every item "input" if it's empty don't call a function pressed on the button

我的代码不适用于所有对象,

my code works for first object not all,

状态

 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

For answer @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>
       );
      });
  };

推荐答案

如果要检查的每个属性都具有length > 0,则可以在项目上循环并添加isValid键.

You can loop on the items and add a isValid key if every property to check has a length > 0.

const toolsUsed = [
  {
    id: 0,
    name: 'first',
    price: '2',
    count: '4',
  },
  {
    id: 1,
    name: 'second',
    price: 1,
    count: 8,
  },
]

const validToolsUsed = toolsUsed.map(item => ({
    ...item,
    isValid: ['name', 'price', 'count']
      .every(key => item[key].length > 0 )
  })
)

这篇关于如何检查数组中的每个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:49