是否可以通过mapStateToProps设置属性,并使用setState更改状态并将该信息保存到我的数据库中?数据是从Google Books API返回的,我想保存一小部分数据。
我的状态:
state = {
title: '',
subtitle: '',
authors: '',
description: '',
thumbnail: '',
buyLink: ''
};
用于setState并保存到数据库的功能
let { book } = this.props.book;
let bookInfo;
if (book !== null) {
const onSave = (e) => {
e.preventDefault();
let savedData = this.setState({
title: book.volumeInfo.title,
subtitle: book.volumeInfo.subtitle,
authors: book.volumeInfo.authors,
description: book.volumeInfo.description,
thumbnail: book.volumeInfo.imageLinks.thumbnail,
buyLink: book.saleInfo.buyLink
});
console.log(savedData);
};
// this.props.saveBook(savedData, this.props.history);
bookInfo = <BookInfo book={book} onClick={onSave} />;
}
savedData返回未定义
const mapStateToProps = (state) => ({
book: state.books
});
答案 0 :(得分:3)
要save
到数据库,根本不需要调用setState()
。 State和Props只是React用来管理数据以及与数据交互的机制(这过于简化)。
查看您的代码,只需要将book
对象转换为较小/不同的格式。
saveData = () => {
// The code below just shows intention and shouldn't be used as is.
let book = this.props.book
let bookToSave = {
title: book.volumeInfo.title,
subtitle: book.volumeInfo.subtitle,
authors: book.volumeInfo.authors,
description: book.volumeInfo.description,
thumbnail: book.volumeInfo.imageLinks.thumbnail,
buyLink: book.saleInfo.buyLink
}
this.props.save(bookToSave, this.props.history);
}
render() {
<BookInfo book={this.props.book} onSave={this.saveData} />
}
我对您的流程的了解似乎是:
基于上述情况,我认为您无需将书复制到某种状态。
答案 1 :(得分:2)
如果要记录saveData,则需要使用setState回调,如下所示:
this.setState({
title: book.volumeInfo.title,
subtitle: book.volumeInfo.subtitle,
authors: book.volumeInfo.authors,
description: book.volumeInfo.description,
thumbnail: book.volumeInfo.imageLinks.thumbnail,
buyLink: book.saleInfo.buyLink
}, ()=>{
console.log(this.state)
this.props.saveBook(this.state, this.props.history);
});