I have the code snippet as below:
state variables:
state = {
value: 'default value',
items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}
inside render function:
this.state.items.map((data, key) => (
// I want to set the state of 'value' here something like this
this.setState({ value: 'somevalue' })
))
I want to map through the array and check for a particular id
in the array say, if the array contains an id = 1
, then set the state value
as t1
, similarly, if an array contains an id = 2
, then set the state of value
as t2
.
Inside map
function, we can't set the state repeatedly. What would be the alternative for this?
You don't need to (and should not) set a state inside any loop.
In this example, you simply need to find
the matching item and, if found, set its value in the state, as shown below:
const { Component } = React class App extends Component { constructor(props) { super(props) this.state = { value: 'default value', items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}] } } handleClick = (id) => { const found = this.state.items.find(item => item.id === id) if (found) { this.setState({value: found.title}) } } render() { return ( <div> value: {this.state.value} <br/> <button onClick={() => this.handleClick(1)}>Click (1)</button> <button onClick={() => this.handleClick(2)}>Click (2)</button> </div> ) } } ReactDOM.render(<App />, document.getElementById("root"))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="root"></div>
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.