如何在道具中计算和传递数组?

时间:2017-12-11 06:18:24

标签: reactjs react-redux react-props

我使用react-form创建一个简单的表单,并希望将项目列表传递给Select组件。 Select组件是react-form库的一部分。

我想将fooItems传递给Select

Select组件

的必需结构
selectItems = [{
  value: 1,
  label: 'a',
}, {
  value: 2,
  label: 'b',
}]

我首先想要过滤从Redux fooItems

收到的mapStateToProps数组
fooItems = [{
  id: 1,
  name: 'a',
  parent: 'P',
  child: 'C'
}, {
  id: 2,
  name: 'b',
  parent: 'P',
  child: 'C'
}]

我试图在将道具传递给组件

时实现一个功能
render() => (
    <Select
    field = "foo"
    id = "foo"
    options = {
      () => {
        return this.props.fooItems.map(e => {
          return {
            label: e.name,
            value: e.id
          }
        })
      }
    }
    />)

但我得到以下错误

Uncaught TypeError: Cannot read property 'find' of undefined
at t.value (index.js:1)

The above error occurred in the <t> component:
in t (created by r)

1 个答案:

答案 0 :(得分:3)

Options字段需要一个对象数组,但是您传递的是一个函数。您需要调用该函数

render() => (
    <Select
    field = "foo"
    id = "foo"
    options = {
      () => {
        return this.props.fooItems.map(e => {
          return {
            label: e.name,
            value: e.id
          }
        })
      }();
    }
 />)

或者你应该直接返回地图的结果

render() => (
    <Select
    field = "foo"
    id = "foo"
    options = {this.props.fooItems.map(e => {
          return {
            label: e.name,
            value: e.id
          }
        })
    }
 />)