I am new to React and wanted to add new data into array state but faced an error:
Expected an assignment or function call and instead saw an expression
getTitle(title) {
axios
.get(
`http://api.openweathermap.org/data/2.5/forecast?q=${title}&APPID=7ad09d078633b652ecef8587a337639e&units=metric`
)
.then(res => {
// this.setState({ title: res.data.city });
this.setState(prevState => {
title: [...prevState.title, res.data.list]; //Here I get the error
});
});
}
setState
needs to return an object representing the new state. Quickest fix is to wrap the body of that arrow function in parentheses:
this.setState(prevState => ({
title: [...prevState.title, res.data.list],
}));
Now it's returning a json object
I think you forgot to return, try this:
this.setState(prevState => ({
title: [...prevState.title, res.data.list] //Here I get the error
}))
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.