React 中受控组件列表

问题描述 投票:0回答:1

我正在尝试创建一个组件列表,其中每个组件都接受用户输入并具有单独的状态。 然后我希望能够过滤此列表并获取例如“switch”为 true 的组件。我已经尝试了很多事情,但似乎我无法弄清楚如何做到这一点。最后我这样做了:

我的父组件

export const Parking = () => {

const [position, setPosition] = useState([false,false,false])

const onBayClick = (index) => {
  
  position[index-1] === false? setPosition([...position.slice(0, index) , true, ...position.slice(index + 1)]):setPosition([...position, false])
}

const myBays = []
for (let i = 1; i < 4; i++) {
  myBays.push(<BayForm key = {i} child = {i}  state = {position[i]} onClick = {onBayClick}/>)
}
const [filteredBays, setFilteredBays] = useState(myBays)
const filterBays = () => {
  setFilteredBays(myBays.filter(bay => {
    return bay.position === false
  }))
}



return (
  <>
    
    {myBays}
   
    

  </>
)

}

我的子组件。我只发布相关部分,因为它太长了。

 const handleClick = () => {
onClick(index)

}

 <FormGroup>
      <FormControlLabel control={<Switch checked = {state} onChange = {handleClick}  color = 'warning'/>} label="Switch"  />
</FormGroup>

但是当我尝试轻按开关时,出现以下错误:

“警告:组件正在将不受控制的输入更改为受控制。这可能是由于值从未定义更改为已定义值导致的,这种情况不应该发生。在组件的生命周期内决定使用受控或不受控制的输入元素更多信息:https://reactjs.org/link/control-components%s”

这样做的正确方法是什么?无论我尝试什么,我都会遇到错误。

reactjs list input filter controlled-component
1个回答
0
投票

嗯,我怀疑你确实将未定义的值从

Parking
传递到了
Switch
,就在这里:

for (let i = 1; i < 4; i++) {
    myBays.push(<BayForm key = {i} child = {i}  state = {position[i]} onClick = {onBayClick}/>)
}

您的填充数组

position[i]
有 3 个值,因此有效索引为 0、1 和 2。

所以将其设置为:

for (let i = 0; i < position.length; i++)

如果您需要在

BayForm
中渲染此索引,只需将
1
添加到其中


另请参阅此处的问题:

const onBayClick = (index) => {
    position[index-1] === false
        ? setPosition([...position.slice(0, index) , true, ...position.slice(index + 1)])
        : setPosition([...position, false])
}

这行

setPosition([...position, false])
的意思是获取现有数组,复制它并与false组合,这会导致数组每次都会增长。 为了以不可变的方式更改数组中的一个值,我建议使用 map 函数:

const onBayClick = (bayIndex) => {
    setPosition(previousPositions => previousPositions.map((it, index) => { // iterating through the array
    if (index === bayIndex) { // if the clicked index matches this one we iterate
        return !it // just set it's opposite value
    }
    return it // otherwise keep it as it is
    }))
}
© www.soinside.com 2019 - 2024. All rights reserved.