我有一个表单,它将对象数组传递给另一个React功能组件:
import React, { useState } from 'react'
import uuid from 'uuid/v1';
const NewMovieForm = ( {addMovie }) => {
const movies = [
{title: 'Generic Action Movie', director: 'Some Guy', id: uuid()},
{title: 'Jumpscare Horror Flick', director: 'Some Guy', id: uuid()},
{title: 'Romantic Comedy Drama', director: 'Some Guy', id: uuid()},
]
const handleSubmit = (e) => {
e.preventDefault();
addMovie(movies);
}
return (
<form onSubmit={handleSubmit}>
<input type="submit" value="add movie" />
</form>
)
}
export default NewMovieForm
其他功能部件:
const SearchAPIResults = () => {
const [movieList, setMovies] = useState([
{ title: 'Weird Space Movie', director: 'Some Guy', id: 1},
{ title: 'Random Comedy', director: 'Some Guy',id: 2},
{ title: 'Thriller With Nick Cage', director: 'Some Guy',id: 3}
])
const addMovie = (movies) => {
movies.forEach(movie => {
console.log(movie)
setMovies([...movieList, {title: movie.title, director: movie.director, id: movie.id}])
console.log(movieList)
})
}
return (
<div>
<ul>
{movieList.map(movie => {
return (<li key={movie.id}>{movie.title}</li>)
})}
</ul>
<NewMovieForm addMovie={addMovie} />
</div>
)
}
export default SearchAPIResults;
当我按下NewMovieForm
组件中的submit
按钮时,只有{title: 'Romantic Comedy Drama', director: 'Some Guy', id: uuid()},
对象会添加到浏览器中显示的电影列表中。console.log(movie);
输出正确的电影对象,但console.log(movieList)
输出movieList
阵列中的原始3个对象。
setMovies([...movieList, {title: movie.title, director: movie.director, id: movie.id}])
每次调用它时,您都会重置回movieList
中存储的内容,再加上一部额外的电影。因此,由于你连续做了三次,你最终会得到原始列表,再加上最后一部电影。
如果需要在旧状态的基础上创建新状态,则应使用setMovies的回调版本。这保证了您始终使用最新版本:
setMovies(previous => [...previous, {title: movie.title, director: movie.director, id: movie.id}])
不过,在你的情况下,我会取消对setMovies的多次调用,只调用一个:
const addMovie = (movies => {
setMovies(previous => [...previous, ...movies]);
}