简体   繁体   English

Function 不接受更新值 React JS

[英]Function doesn't accept updated value React JS

ascendingDirectionSort has 'true' initial value. ascendingDirectionSort 具有“真”初始值。 It can be changed by dropdownlist.它可以通过下拉列表进行更改。 When it is changed, console.log in the sortData function shows updated value, but only the ascendingDirectionSort==true condition executes, even when it's false.当它改变时,sortData function 中的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 }); };

 <option value={true}>

While you are passing boolean values to the value props, they will be rendered as HTML attributes and so will be converted to strings .当您将 boolean 值传递给value道具时,它们将呈现为 HTML 属性,因此将转换为字符串

 if(ascendingDirectionSort){

You are testing the truthiness of the value of that variable.您正在测试该变量值的真实性。

true , "true" and "false" are all true values. true"true""false"都是值。


Use strings consistently.始终使用字符串。

this.state={
  ascendingDirectionSort:"true"
}

and

if(ascendingDirectionSort === "true"){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM