使用useState钩子触发setState后,.map不是函数

时间:2020-10-17 14:34:08

标签: javascript hook

该组件将首次呈现,但是当我触发handleControls函数时,错误表明该不是一个函数,基本上是说我触发handleControl函数后,我的成分状态变得不确定。我暂时在这个问题上摸不着头脑,不知道如何解决,请给兄弟一个帮助!!!预先谢谢你!

//useState
const [ingredients, setIngredients] = useState([{
  id: 1,
  name: 'flour',
  calories: '1520 / 362',
  protein: 7.9,
  fat: 6.6,
  fiber: 3.3,
  carbs: 3.3,
  cholersterol: 0.2,
  vitaminc: 0.2,
  controls: false
}])

更改控件值的功能

function handleControl(e, index) {
  let value = e.target.value
  setIngredients(state => {
    state.ingredents[index].controls = !value
    return (
      // { ...prevIngredient, controls: !prevIngredient.controls}
      { ...state }
    )
  })
}

要渲染的组件

<TableBody>
  {ingredients && ingredients.map((ingredient,index) => (
  <TableRow>
    <TableCell component="th" scope="row">
      {ingredient.id}
    </TableCell>
    <TableCell align="left">{ingredient.name}</TableCell>
    <TableCell align="left">{ingredient.calories}</TableCell>
    <TableCell align="left">{ingredient.protein}</TableCell>
    <TableCell align="left">{ingredient.fiber}</TableCell>
    <TableCell align="left">{ingredient.fat}</TableCell>
    <TableCell align="left">{ingredient.carbs}</TableCell>
    <TableCell align="left">{ingredient.cholesterol}</TableCell>
    <TableCell align="left">{ingredient.vitaminc}</TableCell>
    <TableCell align="left">
      { // ingredient.controls // ? //
       <>
        // <button className={ingredient.id}>Save</button> // <button className={ingredient.id}>Cancel</button> //
        </> // :
        <>
          <button onClick={ (e)=>{handleControl(e,index)}} value={ingredient.controls} className={ingredient.id}>Edit</button>
          <button className={ingredient.id}>Delete</button>
        </> 
       }
    </TableCell>
  </TableRow>
  )) }
</TableBody>

1 个答案:

答案 0 :(得分:0)

您正在通过此行将列表转换为对象

 setIngredients(state => {
    state.ingredents[index].controls = !value
    return (
      // { ...prevIngredient, controls: !prevIngredient.controls}
      { ...state }
    )
  })

您应该只将New State作为数组返回,如下所示:

 setIngredients(state => {
    state[index].controls = !value
    return state
  })