首页 > 解决方案 > 第一次点击后反应按钮不显示结果,我该如何解决?

问题描述

我有一个反应组件,可以显示数据库中的所有书籍。但是,当我第一次单击该按钮时,它不会列出书籍,但是如果我再次单击该按钮,它将列出所有书籍,我如何仅单击一次就可以列出所有书籍?

import PropTypes from "prop-types";
import {getBook} from "../actions/bookActions";
import {connect} from "react-redux";
import {Container} from "@material-ui/core";
import {Table} from "react-bootstrap";
import {Button} from "react-bootstrap";

const bookList = []

class BookListing extends Component {
    constructor(){
        super();

        this.state= {
            id: "",
        };

        this.onSubmit = this.onSubmit.bind(this);

    }

    async onSubmit(e){
        this.setState({[e.target.name]: e.target.value});
        e.preventDefault();
        const data = await this.props.getBook();

        try {
            console.log(data);
            bookList.splice(0, bookList.length)
            data.forEach(book => {
                console.log(book)
                bookList.push(book)
            })
        }catch (exception){
            console.log("no books")
        }
    }

    render() {
        const { errors } = this.state;
        return (
            <Container>
                <form onSubmit={this.onSubmit}>
                    <Button variant="dark" type="submit">Show</Button>{' '}
                    <p>Double click the button</p>
                </form>

                <h2 color={"green"}>{"\n"}Books found {"\n"}</h2>
                <br/>
                <br/>
                <Table striped bordered hover variant="dark">
                    <thead>
                    <tr>
                        <th>Book Id</th>
                        <th>Title</th>
                        <th>Author</th>
                        <th>Category</th>
                    </tr>
                    </thead>
                    <tbody>
                    {bookList.map((book => <tr>
                        <td>{book.id}</td>
                        <td>{book.title}</td>
                        <td>{book.author}</td>
                        <td>{book.category}</td>
                    </tr>))}
                    </tbody>
                </Table>
            </Container>


        )
    }
}

BookListing.propTypes = {
    createProject: PropTypes.func.isRequired
};

export default connect(null, {getBook})(BookListing);

按下按钮一次后的页面:在此处输入图像描述 没有书籍显示,但控制台指示它在那里。

第二次按下按钮后的页面:在此处输入图像描述 这次列出了书籍。

标签: javascriptreactjs

解决方案


由于您需要对 的更改做出反应bookList,因此它需要成为状态的一部分。

this.state = {id:'', bookList: [] }

用来自 的书籍onSubmit替换。bookListdata

// slice without arguments clones an array
this.setState({bookList: data.slice()});

在 React 中更新状态数组时,应该使用concat, slice, filter,mapconcat不是push,splice[]。前者返回一个新数组。后者修改现有的状态数组,可能会被react忽略。有关更多详细信息,请参阅本文上面代码中的切片,可能不是真的需要。(仅用于演示。)

最后,在渲染<tr>s 列表时,您需要为每个 s 指定一个唯一键<tr>。您可以book.id用作键。

<tr key={book.id}>

推荐阅读