簡體   English   中英

單擊按鈕后組件未讀取新的狀態更改

[英]Component isn't reading new state change after button click

基本上我有一個按鈕,當我點擊它時,它會改變狀態的值,在我的父組件中,狀態被讀取並檢查該值並根據該值顯示一些 HTML。 然而,父母的狀態似乎並沒有真正改變。

孩子正在修改handleClick()函數父組件中的displayOptions

class Home extends React.Component {
  constructor(props){
  super(props)
  this.state = {
    dataType: "", // store the type of data for the type of operation that should be sent to the backend. For example "create" will have the data for creating data
    data: {},
    displayOptions: false,
    leads: []
    } 

    // have CRUD options that are displayed when user clicks on a lead. When on of the options are selected
    // display the appropriate fields
  }
  leads = []
  async handleChange(event){
    event.preventDefault()
    // use console.log here otherwise it won't show the desired value for state on the first click
    // this.setState({displayOptions: true}, () => console.log(this.state)) 
    // now get the details for each lead from backend

  }

  async componentDidMount() {
    var leads = await getAllLeads((data) => {return data});
    leads = JSON.parse(leads)
    this.setState({ leads });
    console.log("REF", this.state.displayOptions)
  }

  // <HomePage dataState={this.state}/>
  // then if the dataType isn't empty display the HTML for those fields
  // 
  render() {
    // when one of the leads is clicked, display options
    if(this.state.dataType === "" && this.state.displayOptions === true){
        console.log("DISPLAY OPTIONS")
        return (
          <div className="App">
            <h1> Select a lead</h1>
            <Card Obj={this.state} />
          </div>
        )

    }
    return (
        <div className="App">
          <h1> Select lead {this.state.displayOptions} </h1>
          <Card Obj={this.state} />
        </div>
      )
  }
}

export default Home;

改變它的props子組件

import React, { Component } from 'react';

class Card extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showMenu: false,
    };

    this.showMenu = this.showMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
  }

  showMenu(event) {
    event.preventDefault();

    this.setState({ showMenu: true }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  closeMenu(event) {

    if (!this.dropdownMenu.contains(event.target)) {

      this.setState({ showMenu: false }, () => {
        document.removeEventListener('click', this.closeMenu);
      }); 

    }
  }

  handleClick(arg){
      console.log("HEREw", arg)
      this.props.Obj.displayOptions = arg
      console.log(this.props.Obj)
  }

  render() {
    //console.log("SUPPLIER", this.props)
    return (
      <div>
        {this.props.Obj.leads.map(lead => <a href={lead.first_name} onClick={this.showMenu}> 
            {lead.first_name} {lead.last_name} <br /><br /></a>)} 
        {
          this.state.showMenu
            ? (
              <div
                className="menu"
                ref={(element) => {
                  this.dropdownMenu = element;
                }}
              >
                <button value="update" onClick={() => this.handleClick(true)}> Update </button>
                <button value="create" onClick={() => this.handleClick(true)}> Create </button>
              </div>
            )
            : (
              null
            )
        }
      </div>
    );
  }
}

export default Card

在我console.log之后, displayOptions的值是子組件中的正確值,而不是父組件中的值,謝謝

您不能通過將其設置為新值來完全更新道具。 盡管看起來像Card更新了道具,但它只是實際props的副本,如果您需要它,它永遠不會在您的組件中呈現。

如果你想修改Card displayOptions ,你需要傳入一個回調函數作為Card的 prop。

例如:

// in App.js 
updateDisplayOptions = (newOptions) => {
  this.setState({displayOptions: newOptions})
}}

// in App.js render()
return (
  <div className="App">
    <h1> Select lead {this.state.displayOptions} </h1>
    <Card Obj={this.state} updateOptions={updateDisplayOptions}/>
  </div>
)

// in Card.js
handleClick(arg){
  this.props.updateOptions(arg)
  // right after, Obj won't be updated, but it will asynchronously update, then 
  // rerender your React components, with the newly updated display options
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM