2017-09-05 61 views
2

我想从列表中获得一个随机物品。 到目前为止,我设法把我的列表放在一个数组中,我试图让我需要的一个函数的项目,但我需要它的地方,它是未定义的! 我不知道我错在哪里!从属性物品列表中获得随机物品通过反应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]]; 
}