[英]React child component not re-rendering on state update
The code below is my slimmed down app.下面的代码是我精简的应用程序。 I have an exercise state in the parent which has a value at exercise[index].remainingSets.
我在父项中有一个锻炼状态,它在锻炼 [index].remainingSets 中有一个值。 I update this value in the parent when a child element is clicked by having an onClick which calls
completedSet
function.当通过调用
completedSet
函数的 onClick 单击子元素时,我会在父元素中更新此值。 I print this value on the screen in the child, but when this value changes the printed value in the child does not change.我在孩子的屏幕上打印这个值,但是当这个值改变时,孩子的打印值不会改变。 I see that the props in the child has changed with the react extension but no re-render/update.
我看到孩子中的道具随着反应扩展而改变,但没有重新渲染/更新。
This is what the parent looks like.这就是父母的样子。
const [exercise, setExercise] = useState([]);
const completedSet = (e, index) => {
let completedSetExercise = exercise;
completedSetExercise[index].remainingSets -= 1;
setExercise(completedSetExercise);
e.target.style.backgroundColor = '#CD5C5C';
}
return(
<>
<ExerciseForm onSubmit={onSubmit} />
{Object.keys(exercise).map(key => <Exercise
key={key}
index={key}
exercise={exercise[key]}
/>)}
</>);
}
export default App;```
```import React, {useState, useEffect} from 'react';
const Exercise = (props) => {
const sets =[]
for (var i = 0; i < props.exercise.Sets; i++) {
sets.push(
<li
className="exercise_reps"
onClick={(e) => props.completedSet(e, props.index)}
key={i}>
<span> {props.exercise.Reps} </span>
</li>
)
}
return (
<div>
<div className="exercise_title">
<h2>{props.exercise.Exercise}</h2>
<button onClick={() => props.removeExercise(props.index)}>Remove Exercise</button>
</div>
{props.exercise.remainingSets}
</div>
)
}
export default Exercise;
Issue was I was making and passing a shallow copy to child so it did not see it as different.问题是我正在制作一个浅拷贝并将其传递给孩子,因此它认为它没有什么不同。 I used the spread operator and assigned state to a new variable before assigning it.
我在分配之前使用了扩展运算符并将状态分配给了一个新变量。
let completedSetExercise = [...exercise]
` let completedSetExercise = [...exercise]
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.