Rendering an array.map() in React

前端 未结 9 1910
渐次进展
渐次进展 2020-12-04 11:17

I am having a problem where I am trying to use array of data to render a

    element. In the code below the console.log\'s are working fine,
相关标签:
9条回答
  • 2020-12-04 12:11

    You are not returning. Change to

    this.state.data.map(function(item, i){
      console.log('test');
      return <li>Test</li>;
    })
    
    0 讨论(0)
  • 2020-12-04 12:12

    Using Stateless Functional Component We will not be using this.state. Like this

     {data1.map((item,key)=>
                   { return
                    <tr key={key}>
                    <td>{item.heading}</td>
                    <td>{item.date}</td>
                    <td>{item.status}</td>
                  </tr>
                    
                    })}
    
    0 讨论(0)
  • 2020-12-04 12:13

    I've come cross an issue with the implementation of this solution.

    If you have a custom component you want to iterate through and you want to share the state it will not be available as the .map() scope does not recognize the general state() scope. I've come to this solution:

    `

    class RootComponent extends Component() {
        constructor(props) {
            ....
            this.customFunction.bind(this);
            this.state = {thisWorks: false}
            this.that = this;
        }
        componentDidMount() {
            ....
        }
        render() {
           let array = this.thatstate.map(() => { 
               <CustomComponent that={this.that} customFunction={this.customFunction}/>
           });
    
        }
        customFunction() {
            this.that.setState({thisWorks: true})
        }
    }
    
    
    
    class CustomComponent extend Component {
    
        render() {
            return <Button onClick={() => {this.props.customFunction()}}
        }
    }
    

    In constructor bind without this.that Every use of any function/method inside the root component should be used with this.that

    0 讨论(0)
提交回复
热议问题