从mapStateToProps到setState

时间:2018-07-26 16:36:12

标签: reactjs react-redux

是否可以通过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
 });

2 个答案:

答案 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. 您调用一个API,该API可为您提供大量数据
  2. 您在屏幕上显示此数据
  3. 您允许用户保存它

基于上述情况,我认为您无需将书复制到某种状态。

答案 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);
               });