javascript - 如何在 React 中的 map 函数中设置状态?
问题描述
我的代码片段如下:
状态变量:
state = {
value: 'default value',
items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}
内部渲染函数:
this.state.items.map((data, key) => (
// I want to set the state of 'value' here something like this
this.setState({ value: 'somevalue' })
))
我想通过数组进行映射并检查数组中的特定id
内容,例如,如果数组包含 an id = 1
,则将状态设置value
为t1
,类似地,如果数组包含 an id = 2
,则将状态设置value
为t2
。
在map
函数内部,我们不能重复设置状态。什么是替代方案?
解决方案
您不需要(也不应该)在任何循环中设置状态。
在本例中,您只需要find
匹配项,如果找到,将其值设置为状态,如下所示:
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>
推荐阅读
- ios - 使用 Xamarin UITest 在 iOS 选取器中选择一个项目?
- c# - C# 获取带有超过一年附件的电子邮件
- c - 如何在 C 中使用 char 数组添加两个大的非负整数?
- jenkins - 我无法在后台启动 Jenkins(地址已在使用中)
- cluster-analysis - 如何处理插补没有意义的 NaN 值?(对于 PCA)
- c# - 如何在 MVC 中获取视图以正确引用所需的模型
- angular - Angular 7,递归对象表行
- android - React Navigation 速度极慢
- reactjs - react 最好的表格插件是什么?就像我们在 jquery 中有 DataTable
- ruby-on-rails - 如何在 Rails 中等待而不阻塞主线程?