You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React按钮首次点击不展示书籍列表,需点击两次才生效如何修复?

问题原因

  • 你当前把bookList定义为组件外的普通全局变量,React 组件只有在自身state或传入的props发生变更时才会触发重新渲染。
  • 首次点击按钮时,你修改了bookList的内容但没有触发组件更新,所以页面不会渲染新数据;第二次点击时,提交事件先执行了this.setState操作触发组件重渲染,才把第一次已经修改的bookList内容渲染出来,所以才会出现两次点击才生效的问题。
  • 额外问题:你当前的propTypes配置错误,声明的是不存在的createProject方法,实际注入的是getBook。

修复后的完整代码

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";

class BookListing extends Component {
    constructor(){
        super();
        // 把书籍列表放到组件state中管理
        this.state= {
            bookList: []
        };
        this.onSubmit = this.onSubmit.bind(this);
    }

    async onSubmit(e){
        e.preventDefault();
        try {
            const data = await this.props.getBook();
            // 更新state触发组件重渲染
            this.setState({
                bookList: data
            })
        }catch (exception){
            console.log("no books")
        }
    }

    render() {
        const { bookList } = this.state;
        return (
            <Container>
                <form onSubmit={this.onSubmit}>
                    <Button variant="dark" type="submit">Show</Button>{' '}
                </form>

                <h2 style={{color: "green"}}>
                    找到的书籍
                </h2>
                <br/>
                <br/>
                <Table striped bordered hover variant="dark">
                    <thead>
                    <tr>
                        <th>书籍ID</th>
                        <th>标题</th>
                        <th>作者</th>
                        <th>分类</th>
                    </tr>
                    </thead>
                    <tbody>
                    {bookList.map((book => <tr key={book.id}>
                        <td>{book.id}</td>
                        <td>{book.title}</td>
                        <td>{book.author}</td>
                        <td>{book.category}</td>
                    </tr>))}
                    </tbody>
                </Table>
            </Container>
        )
    }
}

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

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

主要修改点

  • 删除了全局的bookList变量,把书籍列表放到组件的state中管理
  • 移除了无用的id state 和错误的表单赋值逻辑
  • 请求拿到书籍数据后直接通过setState更新bookList,自动触发组件重渲染
  • 修正了propTypes的配置,把不存在的createProject改为实际使用的getBook
  • 给表格行添加了key属性,修复React列表渲染警告
  • 修正了h2标签的颜色写法,把不生效的color属性改为style配置

内容的提问来源于stack exchange,提问作者Kirix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:54:03