组件将是第一次渲染,但当我触发handleControls函数时,错误表明ingredients.map不是一个函数,这基本上是说在我触发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>
您正在通过将列表转换为对象
setIngredients(state => {
state.ingredents[index].controls = !value
return (
// { ...prevIngredient, controls: !prevIngredient.controls}
{ ...state }
)
})
您应该只将New State作为数组返回,如下所示:
setIngredients(state => {
state[index].controls = !value
return state
})