【问题标题】:Function doesn't accept updated value React JS函数不接受更新值 React JS
【发布时间】:2021-12-03 04:36:49
【问题描述】:

ascendingDirectionSort 具有“真”初始值。它可以通过下拉列表进行更改。当它被改变时,sortData 函数中的 console.log 显示更新的值,但只有ascendingDirectionSort==true 条件执行,即使它是假的。

   ...Class
   ...constructor
this.state={
  ascendingDirectionSort:true
}
render()...
const {ascendingDirectionSort}=this.state


const sortData(field)=>{
  console.log(ascendingDirectionSort)//true, when ascendingDirectionSort=true and false when = false
  if(ascendingDirectionSort){
  execute1...//always executes
  console.log(ascendingDirectionSort)
  }else{
  execute2...//doesnt work
  
  }

}
...
   <select value = {ascendingDirectionSort} onChange={this.handleChange}>
        <option value={true}>Ascending</option>
        <option value={false}>Descending</option>
    </select>
...

handleChange = (event) => {
  this.setState({ ascendingDirectionSort: event.target.value });
};

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:
    <option value={true}>
    

    当您将布尔值传递给 value 属性时,它们将被呈现为 HTML 属性,因此将被转换为 字符串

    if(ascendingDirectionSort){
    

    您正在测试该变量值的真实性。

    true"true""false"所有 true 值。


    一致地使用字符串。

    this.state={
      ascendingDirectionSort:"true"
    }
    

    if(ascendingDirectionSort === "true"){
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 1970-01-01
      • 2017-12-11
      • 2018-09-16
      • 1970-01-01
      • 2017-10-30
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多