为了账号安全,请及时绑定邮箱和手机立即绑定

组件确实更新,但 if 语句不起作用

组件确实更新,但 if 语句不起作用

Helenr 2023-07-20 16:20:20
我在我的反应代码中发现了一个奇怪的行为。我对反应还很陌生,无法弄清楚。在过去的几天里,我创建了一个不错的仪表板,并想添加一个包含 CRUD 事务的数据页面。当 searchForm 状态为 true 时,我想更改搜索按钮内的文本,但它仅在组件更新后起作用,而不是在第一次渲染时起作用。我已将 searchForm 状态设置为 false,并在 searchBtnClick 上将状态设置为 true。但按钮内的文本不会改变。
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

我对这段代码提出一些建议:


这是一种个人偏好,使用箭头表示法来定义类方法,这样您就不必.bind(this)为每个方法都定义了。

// this is the same as

constructor(props) {

  this.someFunc = this.someFunc.bind(this)

}

someFunc() {}


// writing just this

someFunc = () => {}

您内部的代码if (this.state.error) {}几乎与整个组件相同,只是做了一些细微的更改。我建议您的 if 语句更有针对性/具体,只需更改所需的最小部分即可。(参见下面的大代码)


在一些地方,您使用三元运算符来返回某些内容 OR a <Fragment />。同样,这可能只是个人喜好,但您可以使用它&&来简化代码。


// this is the same as

{this.state.searchForm ? (

  <MyComponent />

) : (

  <Fragment />

)}


// is the same as writing

{this.state.searchForm && <MyComponent />}


// or

{this.state.searchForm && (

  <MyComponent

    foo="something"

    bar="baz"

    onClick={this.onClick}

  />

)}

这是应用了上面的简化的完整代码示例。


RE:您的实际问题是,为什么文本没有在搜索按钮内交换...您的点击处理程序看起来正确,应该正确更改状态...也许像我建议的那样使用 if 语句,更有针对性仅更改按钮内的实际文本而不是整个按钮会有所帮助。


import React, { Component, Fragment } from "react";


import SideBar from "../../components/navBar/SideBar";

import SearchForm from "../../components/forms/SearchForm";

import TransactionTable from "../../components/tables/TransactionTable";


import "./data.css";


import { getTransaction } from "../../actions/Transactions";


export default class Data extends Component {

  constructor(props) {

    super(props);


    this.state = {

      year: 0,

      month: "",

      transactions: [],

      searchForm: false,

      addForm: false,

      editForm: false,

      error: false,

      errorMessage: "",

    };


    this.months = [

      "January",

      "February",

      "March",

      "April",

      "May",

      "June",

      "July",

      "August",

      "September",

      "October",

      "November",

      "December",

    ];

  }


  componentDidMount() {

    const currentDate = new Date();

    var currentYear = currentDate.getYear() + 1900;

    this.setState({ year: currentYear });

    var currentMonth = this.months[currentDate.getMonth()].toLowerCase();

    this.setState({ month: currentMonth });


    getTransaction({ year: currentYear, month: currentMonth }).then((res) => {

      if (res.error) {

        this.setError(true, res.error);

      } else {

        this.setError(false);

        this.setState({ transactions: res });

      }

    });

  }


  navBtnClick = () => {

    this.props.updateNavBarState();

  };


  addBtnClick = (e) => {

    this.setState({ addForm: !this.state.addForm });

  };


  searchBtnClick = () => {

    this.setState({ searchForm: !this.state.searchForm });

  };


  editBtnClick = (e) => {

    this.setState({ editForm: !this.state.editForm });

  };


  deleteBtnClick = (e) => {};


  updateTable = (transactions) => {

    // If there isn't an error, close the form

    if (this.state.error === false) {

      this.setState({ transactions: transactions });

      this.setState({ addForm: false });

      this.setState({ searchForm: false });

      this.setState({ editForm: false });

    }

  };


  setError = (state, message = "") => {

    this.setState({ error: state });

    this.setState({ errorMessage: message });

  };


  render() {

    return (

      <Fragment>

        <SideBar sideBarState={this.props.sideBarState} />

        <div className="page">

          <div className="grid head">

            <span id="sidebarCollapseBtn">

              <i className="fas fa-align-left" onClick={this.navBtnClick}></i>

            </span>

            <h1 className="capitalize">data</h1>

          </div>

          <div className="content">

            <div className="card" id="dataCard">

              <div className="actions" id="actions">

                <div className="flex">

                  <button

                    className="search btn"

                    id="searchBtn"

                    onClick={this.searchBtnClick}

                  >

                    {this.state.searchForm ? (

                      "close"

                    ) : (

                      <Fragment>

                        <i className="fas fa-search mr-025"></i>search

                      </Fragment>

                    )}

                  </button>

                  <button

                    className="add btn"

                    id="addBtn"

                    onClick={this.addBtnClick}

                  >

                    <i className="fas fa-plus mr-025"></i>add

                  </button>

                </div>

                {this.state.searchForm && (

                  <SearchForm

                    year={this.state.year}

                    month={this.state.month}

                    updateTable={this.updateTable}

                    setError={this.setError}

                  />

                )}

              </div>

              <div className="output">

                {this.state.error && <h2>{this.state.errorMessage}</h2>}

                {this.state.transactions.length > 1 && (

                  <TransactionTable transactions={this.state.transactions} />

                )}

              </div>

            </div>

          </div>

        </div>

      </Fragment>

    );

  }

}



查看完整回答
反对 回复 2023-07-20
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信