Javascript 如何在React中设置map函数内部的状态?
我的代码片段如下所示: 状态变量:Javascript 如何在React中设置map函数内部的状态?,javascript,reactjs,Javascript,Reactjs,我的代码片段如下所示: 状态变量: 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: 'somev
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' })
))
内部渲染功能:
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
,例如,如果数组包含id=1
,则将状态值设置为t1
,类似地,如果数组包含id=2
,则将值的状态设置为t2
在map
函数中,我们不能重复设置状态。有什么替代方法呢?您不需要(也不应该)在任何循环中设置状态
在本例中,您只需找到匹配项,如果找到,则在状态中设置其值,如下所示:
const{Component}=React
类应用程序扩展组件{
建造师(道具){
超级(道具)
此.state={
值:“默认值”,
项目:[{id:1,标题:'t1'},{id:2,标题:'t2'}]
}
}
handleClick=(id)=>{
const found=this.state.items.find(item=>item.id==id)
如果(找到){
this.setState({value:found.title})
}
}
render(){
返回(
值:{this.state.value}
this.handleClick(1)}>单击(1)
this.handleClick(2)}>单击(2)
)
}
}
ReactDOM.render(,document.getElementById(“根”))
例如:data=['id:1,'title':'这是第一个值,'id:2,'title':'这是第二个值]。我将一个名为newVariable的状态变量设置为0。现在,我想映射数组并检查数组中的特定字符串,比如说,如果数组包含字符串“first”,则将state varaible newVariable设置为first,类似地,如果数组包含字符串“second”,则将newVariable的状态设置为second。我想实现这样的目标。正如@AjeetShah提到的,在render()中调用setState()
,似乎是不对的。。。检查一下:您可以使用forEach而不是map,但是正如前面提到的,它没有任何意义。。。