如何检查数组中的每个项目?

时间:2019-12-21 15:43:46

标签: javascript arrays reactjs loops

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

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

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

状态

 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>
       );
      });
  };

3 个答案:

答案 0 :(得分:1)

如果要检查的每个属性都有一个isValid,则可以循环显示这些项目并添加一个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 )
  })
)

答案 1 :(得分:0)

您的操作方式仅设置了第一项的状态,  调用setState后会触发重新渲染,可能是您遇到了问题  可能Array.reduce会为您

尝试

 const isValid =  toolsUsed.reduce((acc, curr) => {
  if(curr.name.length && curr.price.length && curr.count.length) {
     return true
   }
   return false
   }, false
   )
this.setState({isValid })

如果您有任何codeandbox示例,请共享,以便优化功能,请注意,reduce fution的第二个参数是累加器acc的初始值,可能是您需要对其进行调整使您的实际功能正常工作

请随时提问

答案 2 :(得分:0)

一种检查对象数组中除input之外的所有id是否等于''

的一种方法
renderToolsUsed = () => {
    return this.state.toolsUsed.map((item, index) => {
      delete item.id;
      if (Object.keys(item).every(key => item[key] !== '')) {
        ...
      }
      // If you want to use id later
      if (Object.keys(item).every(key => key === 'id' ? true : item[key] !== '')) {
      ...
      }

    }

关于状态,您可能希望使用数组来存储多个状态,例如通过id或索引

this.setState({valid: [...this.state.valid, index]})

然后通过检查ID是否在您的状态下进行证明

 pressed = (viewDisplayIndex) => {
    if(this.state.vaild.include(viewDisplayIndex)){
       call...
    }else{
       ...
    }
  }
相关问题