简体   繁体   中英

How to use an arrow function inside an Array.map() function with react

I have used the map function all over my react application but always passing in an actual declared method. I am currently playing around trying to get an inline arrow function to work as a repeater. Here is the code I'm trying to run inside my render function:

    <DropdownButton id='some-id' title={this.state.myId}>
        {Object.keys(this.state.EMPTPS).map(
            k => (
                <Dropdown.Item key={k} eventKey={k}>{this.state.EMPTPS[k]}</Dropdown.Item>
            )
        )}
    </DropdownButton>

So I'm trying to iterate over a set of keys of an object I've created in my state declaration, and use the values as the button value and the keys as the eventKey, and key. Here is my object in state:

    EMPTPS: {
        'KEY1': 'Value1',
        'KEY2': 'Value2',
        'KEY3': 'Value3'
    }

Whenever this code runs, I get the 'Element type invalid' error from react, so obviously something isn't right here. I'm sure (and hope) it's just a simple syntax error on my part, but seeing as how I am still fairly fresh on ES6 and react in general, help would be much appreciated.

You could use the syntax that uses a return statement instead, sometimes i've been there and trying this solved the issue. I've just added a brackets after the arrow to wrap the logic inside the iteration, and return the element at the end.

 <DropdownButton id='some-id' title={this.state.myId}>
        {Object.keys(this.state.EMPTPS).map( k => {
             return <Dropdown.Item key={k} eventKey={k}>{this.state.EMPTPS[k]}/Dropdown.Item>
            }
        )}
    </DropdownButton>

Well, this was completely unrelated to the syntax. Good news is the code is right. My issue lies with the version of react-bootstrap and bootstrap I have in my app. Because of the size and nature of the app, I can't update to v4.x, which is necessary to run bootstrap-react@1.0.0-beta.5 (the Dropdown.Item element doesn't seem to function outside of this version) as far as I have been able to tell. Anyway, silly issue with a silly solution. Thanks for the suggestions all.

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