简体   繁体   中英

React JSX: rendering nested arrays of objects

I have a component with the following render:

  render() { const { policy } = this.props; let deployment = policy.Deployment; let value = policy.value; let policyLegend = deployment.policyLegend; let policyObj = this.valueToPolicy(policyLegend, value); console.log(policy); console.log(deployment); console.log(value); console.log(policyLegend); console.log(policyObj); return( <div> <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }> { policyLegend.map(function(policy) { <div> <h3 key={ policy.id }>{ policy.displayName }</h3> { policy.values.map(value => { return( <Form.Field key={ value.name }> <label>{ value.displayName }</label> <Checkbox toggle /> </Form.Field> ); }) } </div> }) } <Button name={ 'Submit' } type='submit'>Submit</Button> <Button onClick={ this.props.onCancel }>Cancel</Button> </Form> </div> ) } 
 <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> 

policyLegend is an array of objects with a 'values' array inside each object.

When my application builds, I receive no errors but nothing appears on my component page. I'm not sure where I'm going wrong and would appreciate any advice, thank you.

It's because you do not return anything inside the policyLegend map. Try this:

{
    policyLegend.map((policy) => {
        return (
            <div>
                <h3 key={ policy.id }>{ policy.displayName }</h3>
                {
                    policy.values.map(value => {
                        return(
                            <Form.Field key={ value.name }>
                                <label>{ value.displayName }</label>
                                <Checkbox toggle />
                            </Form.Field>
                        );
                    })
                }
            </div>
        );
    })
}

You are not returning the JSX from your map method. Once you return the JSX you formed :

policyLegend.map(function(policy) {
              return (<div>
                <h3 key={ policy.id }>{ policy.displayName }</h3>
                {
                  policy.values.map(value => {
                    return(
                      <Form.Field key={ value.name }>
                        <label>{ value.displayName }</label>
                        <Checkbox toggle />
                      </Form.Field>
                    );
                  })
                }
              </div>)
            })

You should get the result you're looking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM