React.js获取状态以立即更新

时间:2020-11-12 04:39:25

标签: javascript reactjs react-state

我希望状态更改时能立即显示状态更改,但我似乎无法弄清楚为什么不更改。基本上,当用户单击菜单中的下拉菜单项时,他们单击的菜单项内部文本...应该在屏幕上显示为h1,但只有在下次单击时才会显示。我该如何更改?希望我有道理。可以找到代码here

父组件(APP):

class App extends React.Component {
  state = {
    loading: true,
    bases: ['USD', 'EUR', 'AUD', 'CAD', 'JPY', 'NZD'],
    selectedBase: null
  };

//当组件安装覆盖物持续3秒钟时

  componentDidMount() {
    setTimeout(() => this.setState({
      loading: false,
    }), 3000)

    this.onBaseChange('USD');
  }

//当用户在搜索组件中选择新的基础时,状态将更新

  onBaseChange = newBase => {  
    this.setState({ selectedBase: newBase });
  }

//需要了解如何在状态更新后立即查看状态变化!

//呈现的内容:

  render(){
    return (
      <>
      {this.state.loading === false ? (
      <div className="App">
        <div id="one">
          <h1>{this.state.selectedBase}</h1>
          <Search bases = {this.state.bases} selectedBase = {this.state.selectedBase} onBaseChange = {this.onBaseChange}/>
        </div>
       </div>
        ) : (
          <Overlay />
        )}
        </>
    );
  }
}

  

export default App;

子组件(搜索):


class Search extends Component {
    state = {
        dropdownVisible: false,
        term: '',
        selectedBase: this.props.selectedBase
      };

//当从下拉列表中单击一个碱基时,selectedBase将更新,术语被设置为空,而下拉列表则变为不可见。 //通过prop将孩子的状态传递给父对象 //清除点击时的输入搜索

    onBaseSelect = (event) => {
        // when an base is clicked from dropdown, the selectedBase is updated, term is set back to empty, and dropdown back to nonvisible.
        this.setState({
            selectedBase: event.target.innerHTML,
            term: '',
            dropdownVisible: false
        })

        // passing state of child up to parent through prop
        this.props.onBaseChange(this.state.selectedBase)
        
        // clearing input search on click
        document.getElementById("input_search").value = "";
    }
render(){
        return(
                <div id="search">
                        <div id="dropdown" style={{display: this.state.dropdownVisible ? "block" : "none"}}>
                            <ul>
                                {/* filterng out base array based on users input */}
                                {this.props.bases.filter(base => base.includes(this.state.term.toUpperCase())).map((filteredBase, index) => (
                                        <li onClick = {this.onBaseSelect} key={index}>{filteredBase}</li>
                                ))}
                            </ul>
                        </div>
                 </div>
        )
    }
}

export default Search

1 个答案:

答案 0 :(得分:1)

this.setState是一个异步函数,所以当您这样做

    // passing state of child up to parent through prop
    this.props.onBaseChange(this.state.selectedBase)
    
    // clearing input search on click
    document.getElementById("input_search").value = "";

状态尚未更新。因此,像这样将代码作为回调发送到this.setState,

 onBaseSelect = (event) => {
    // when an base is clicked from dropdown, the selectedBase is updated, term is set 
     back to empty, and dropdown back to nonvisible.
    this.setState({
        selectedBase: event.target.innerHTML,
        term: '',
        dropdownVisible: false
    },
 ()=>{
     // passing state of child up to parent through prop
    this.props.onBaseChange(this.state.selectedBase)
    
    // clearing input search on click
    document.getElementById("input_search").value = "";
  ); 
}