2017-09-05 6 views
2

リストからランダムなアイテムを取得しようとしています。 これまでのところ私のリストを配列に入れて管理していますが、関数が必要な項目を取得しようとしていますが、必要な場所は未定義です! 私はどこが間違っているのか分かりません!!!React jsによってプロパティのあるアイテムのリストからランダムなアイテムを取得します

私は、全体のコードはここにある。このコンソールログ

handleChange(event) { 
    this.setState({value: event.target.value}); 
    var NewDictionary = this.Dictionary; 
    console.log(Rand(NewDictionary)); 
    } 

で結果を見たい:

class Application extends React.Component{ 
    constructor(props) { 
    super(props); 
    this.state = { 
    value:'option2', 
    button:'submit', 
    }; 
    this.Dictionary = { 
    Salam:"Hi", 
    khodafez:"Bye", 
    are: "Yes", 
    na: "No", 
    shab: "Night", 
    rooz: "Day", 
    } 
    this.handleChange = this.handleChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
} 
handleChange(event) { 
    this.setState({value: event.target.value}); 
    var NewDictionary = this.Dictionary; 
    console.log(Rand(NewDictionary)); 
    } 
    handleSubmit(event) { 
    this.setState({button: this.state.value}); 
    event.preventDefault(); 
    } 

    render(){ 
    return(

    <form onSubmit={this.handleSubmit}> 
    <div> {this.Dictionary.Salam} </div> 
    <div className="radio"> 
    <label> 
     <input type="radio" value={this.Dictionary.Salam} 
     checked={this.state.value === this.Dictionary.Salam} 
     onChange={this.handleChange} /> 
     {this.Dictionary.Salam} 
    </label> 
    </div> 
    <div className="radio"> 
    <label> 
     <input type="radio" value="option2" 
     checked={this.state.value === 'option2'} 
     onChange={this.handleChange} /> 
     Option 2 
    </label> 
    </div> 
    <div className="radio"> 
    <label> 
     <input type="radio" value="option3" 
     checked={this.state.value === 'option3'} 
     onChange={this.handleChange} /> 
     Option 3 
    </label> 
    </div> 
    <div className="radio"> 
    <label> 
     <input type="radio" value="option4" 
     checked={this.state.value === 'option4'} 
     onChange={this.handleChange} /> 
     Option 4 
    </label> 
    </div> 
    <button onClick={this.handleSubmit} className="btn btn-default" type="submit">{this.state.button}</button> 
</form> 

    ) 
    } 
} 
function Rand(NewDictionary){ 
    let i = NewDictionary.length - 1; 
    const j = Math.floor(Math.random() * i); 
    return NewDictionary[j]; 
} 
ReactDOM.render(
    <Application />, 
    document.getElementById('root') 
); 
+4

「this.Dictionary」はオブジェクトであり配列ではありません。 –

+3

辞書はオブジェクトであり、配列ではありません。キーの配列を取得するには 'Object.keys(NewDictionary)'を使います。 –

答えて

0

NewDictionaryはそう項目を取得しようと、オブジェクトではなく配列であるためですインデックスでは機能しません。その代わりに、Object.keys(NewDictionary)を使用してキーの配列を作成し、ランダムなインデックスを使用してランダムなキーを取得します。

function Rand(NewDictionary){ 
    const keys = Object.keys(NewDictionary); 
    let i = keys.length - 1; 
    const j = Math.floor(Math.random() * i); 
    return NewDictionary[keys[j]]; 
} 
関連する問題