I'm trying to update an array using useState
hook after button click. I learnt that the state
gets updated asynchronously. I tried to update the state by using an ES6 function inside setMovies
but that does not seem to work. What should I be doing instead?
Could anyone please help?
const [movies, setMovies] = useState([]);
const [movie, setMovie] = useState('');
...
const handleSearch = () => {
return axios({
method: "GET",
url: url
},
params: {
Title: movie,
},
})
.then(({ data }) => {
const { Hits } = data
setMovies(Hits)
})
}
const handleMovieChange = event => {
setMovie(event.target.value)
}
UI
<Grid container>
<Grid item>
<TextField onChange={handleMovieChange} label="Title" />
</Grid>
<Grid item>
<Button onClick={handleSearch}>
Search
</Button>
</Grid>
</Grid>
Your code looks correct. I guess it could be your return format has issue or hits
instead of Hits
. can you log to see if it is lower cases, that is something I have experienced before?
const { Hits, hits } = data;
console.log("Hits:", Hits, hits)
setMovies(Hits)
您可能错过了TextField
的值,因此它无法存储最新的搜索词
<TextField value={movie} onChange={handleMovieChange} label="Title" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.