[英]How to set the state inside map function in React?
I have the code snippet as below:我的代码片段如下:
state variables: state 变量:
state = {
value: 'default value',
items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}
inside render function:内部渲染 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
.我想通过阵列到Z1D78DC8ED51214EFE24490AEZ,并在数组中检查一个特定的id
,如果阵列包含一个id = 2
id = 1
,则设置Z9ED39E2EA2EA2EA931586B6B6B6A985A6942F5338 value
and8 and8 and2 and2 and and ysnay zyney ys id1 ys id1 if as t1
,如果value
为t2
。
Inside map
function, we can't set the state repeatedly.在map
function 内部,我们不能重复设置 state。 What would be the alternative for this?什么是替代方案?
You don't need to (and should not) set a state inside any loop.您不需要(也不应该)在任何循环内设置 state。
In this example, you simply need to find
the matching item and, if found, set its value in the state, as shown below:在本例中,您只需find
匹配项,如果找到,则在 state 中设置其值,如下所示:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.