从循环结果中反应存储道具值

React storing prop value from outcome of loop

是否可以从 React 中的循环结果中存储组件 prop 的值?

我有以下组件:

<CheckboxSemantic 
  defaultChecked={questionItem.answer.map((answerItem, answerItemItemIndex) => {
        if (answerItem.value === questionMapping.value) {                                                                                 
          return true;                                                                                
        }
          return false; 
       })
     } />

此returns以下错误:

Warning: Failed prop type: Invalid prop defaultChecked of type array supplied to Checkbox, expected boolean.

有没有更好的方法可以做到这一点?

问题出在map。它总是 return 一个 array。您需要像下面这样使用 reduce

<CheckboxSemantic 
  defaultChecked={questionItem.answer.reduce((acc, answerItem) => {
        if (answerItem.value === questionMapping.value) {                                                                                 
          acc = true;                                                                                
        }
        return acc; 
       }, false)
     } />

注意:未测试,预计语法错误。