未捕获错误:返回const时,对象无法作为React子项生效

时间:2017-09-26 12:23:55

标签: reactjs redux

我不知道为什么即时通过对象进行映射时会出现此错误。这是代码:

const Leki = (props) => {
        const fakePayload = props.fakePayload;
        const drugs = props.drugs;

        const rngPayloadId = Math.floor(Math.random() * 4);

        const payload = fakePayload.map(payload => {
            if (payload.payloadId === rngPayloadId) {

                return payload.drugsId.map(id => {
                    return <tr>
                        {props.dispatch(setId(uuid(), id))}
                    <td>{id}</td>
                    <td>{drugs[id].name}</td>
                    <td><input value={undefined} type="number" name="price" /></td>
                </tr>
            })
        }
    })
    return(
        <tbody>{payload}</tbody>
    )
}

我该怎么做才能避免这个问题?

2 个答案:

答案 0 :(得分:0)

array.map返回另一个数组。由于仅在payload.payloadId === rngPayloadId时返回结果,因此某些payload条目为空。

尝试使用fakePayload.filter代替。

我做了一个例子,你可以查看一下。

const Leki = ({ fakePayload = [], drugs = [] }) => {
  const rngPayloadId = Math.floor(Math.random() * 4)
  
  const payload = fakePayload
    .filter(payload => payload.payloadId === rngPayloadId)
    .map(payload =>
      payload.drugsId.map(id =>
        <tr key={id}>
          <td>Id: {id}</td>
          <td>{drugs[id].name}</td>
        </tr>
      )
    )
  
  return <tbody>{payload}</tbody>
}

const fakePayload = [{
  payloadId: 0,
  drugsId: [1, 2],
}, {
  payloadId: 1,
  drugsId: [3, 4],
}, {
  payloadId: 2,
  drugsId: [5, 6],
}, {
  payloadId: 3,
  drugsId: [7, 8],
}]
    
const drugs = {
  1: { name: 'Drug 1' },
  2: { name: 'Drug 2' },
  3: { name: 'Drug 3' },
  4: { name: 'Drug 4' },
  5: { name: 'Drug 5' },
  6: { name: 'Drug 6' },
  7: { name: 'Drug 7' },
  8: { name: 'Drug 8' },
}
    
class App extends React.Component {
  render() {
    return (
      <table>
        <Leki fakePayload={fakePayload} drugs={drugs} />
      </table>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
table tr td {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

React不知道如何在{}see this)内呈现对象或数组。当您映射payload.drugsId时,每个id都会成为一个对象,因此像<td>{id}</td>这样引用它会失败。您可以使用{id[0]}或仅<td>{JSON.stringify(id)}<td>来查看每次迭代中的地图结果,并根据需要更改代码。