我Context
用来将exerciseList
数组变量传递给 2 个不同的组件,
ExerciseList
组件和Exercise
组件。
Exercise
组件呈现单个练习,然后
ExerciseList
组件导入并实现它。
但现在的问题是,当有更新时,t.ex 练习已被删除,所以ExerciseList
应该重新渲染。
但除非我刷新页面,否则它不会发生。
这是我Context
的
function ContextProvider(props) {
const [ exerciseList, setExerciseList ] = useState([])
useEffect(() => {
axios.get('http://localhost:5000/exercises/')
.then(response => {
setExerciseList(response.data)
})
.catch(err => console.log(err))
}, [])
return (
<Context.Provider value={{exerciseList,
setExerciseList,
}}>
{props.children}
</Context.Provider>
)
}
export { Context, ContextProvider }
我收到这样的exerciseList
inExerciseList
组件
export default function ExerciseList(){
const { exerciseList } = useContext(Context)
const exerciseData = exerciseList.map( exercise => (
<Exercise key={exercise._id}
id={exercise._id}
username={exercise.username}
description={exercise.description}
duration={exercise.duration}
date={exercise.date}
/>
))
return(
<div>
<h3>Exercise List</h3>
<table className="exercise-table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Duration</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{exerciseData}
</tbody>
</table>
</div>
)
}
Exercise
我有功能的组件delete
是这样的
export default function Exercise({id, username, description, duration, date}) {
const { setExerciseList } = useContext(Context)
const deleteExercise = (id) => {
axios.delete('http://localhost:5000/exercises/' + id)
.then(res => console.log(res.data))
.catch(err => console.log(err))
setExerciseList(exercises => exercises.filter(exercise => exercise.id !== id))
}
return (
<tr>
<td>{username}</td>
<td>{description}</td>
<td>{duration}</td>
<td>{date}</td>
<td>
<Link to={"/edit/" + id}>edit</Link> | <button onClick={() => deleteExercise(id)}>delete</button>
</td>
</tr>
)
}
我想知道为什么?我将console.log(exerciseList.length > 0)
ExerciseList组件放入,看看它是否捕捉到数组的变化,它没有。
帮助!