2017-10-11 177 views
0

我創建了一個用react.js排序選項的下拉菜單,但是我意識到改變React狀態的布爾值是無效的。爲什麼設置true/false值對React狀態不起作用?

  <div className="Sort"> 
       Sort by 
       <select 
       value={this.state.selectValue} 
       onChange={this.sorting} 
       > 
       <option value="index">Pokedex Index</option> 
       <option value="ascecnding">Ascending</option> 
       <option value="descending">Descending</option> 
       </select> 
      </div> 

這裏是我的下拉菜單,並呼籲當一個選項被選中

sorting(e) { 

    if(e.target.value == "index") { 

     this.setState({ 
      indexSort : !this.state.indexSort, 
      ascendSort: !this.state.ascendSort, 
      descendSort: !this.state.descendSort 
     }); 

    } else if(e.target.value =="ascecnding") { 

     this.setState({ 
      indexSort : !this.state.indexSort, 
      ascendSort: !this.state.ascendSort, 
      descendSort: !this.state.descendSort 
     }); 

    } else { 
     this.setState({ 
      indexSort : !this.state.indexSort, 
      ascendSort: !this.state.ascendSort, 
      descendSort: !this.state.descendSort 
     }); 
    } 
} 

這是功能,因爲我不能直接設置像indexSort看起來很醜陋:假的。

有沒有更好的方法來做到這一點?

+0

是不是你的三個條件語句做同樣的事情?難道你不能完全刪除它們嗎,只需在'sorting(e){}'中直接查找這三種類型? –

+0

是的,我忘了改變。但我的問題是如何禁用其他兩個選擇一個時,我不能使用true/false。順便說一下,初始設置是「索引」,因此這開始爲真。 – user6792790

+1

在組件狀態中設置true/false是有效的https://jsfiddle.net/jalissa/mnt376a7/3/ ...也許你的狀態沒有被設置爲true/false的原因是在你的代碼的另一部分。 – Jalissa

回答

1

而不是有三個不同的指標,並打開和關閉他們我認爲你應該有一個單一的真相來源,只改變這個價值。

您的<select>的值來源於該州的selectValue,因此這是您需要更改的唯一值。其他三個狀態屬性(indexSort,ascendSort和descendSort)是不必要的。

活生生的例子:https://codesandbox.io/s/lxqm8wqj5z

import React, { Component} from 'react'; 
import { render } from 'react-dom'; 

class App extends Component { 
    constructor(props) { 
    super(props) 
    this.state = { 
     selectValue: 'index' 
    } 
    this.sorting = this.sorting.bind(this); 
    } 
    sorting(e) { 
    this.setState({ selectValue: e.target.value}, function(){ 
     // see how the state has changed 
     // running inside setState's callback, 
     // otherwise you don't get the real state 
     // due to the normal (expected) delay 
     console.log(this.state.selectValue) 
    }) 
    } 
    render() { 
    return (
     <div> 
     <div className="Sort"> 
      Sort by 
      <select value={this.state.selectValue}onChange={this.sorting}> 
      <option value="index">Pokedex Index</option> 
      <option value="ascending">Ascending</option> 
      <option value="descending">Descending</option> 
      </select> 
     </div> 
     </div> 
    ) 
    } 
} 

render(<App />, document.getElementById('root')); 
相關問題