我正在尝试从列表中随机获取一项。 到目前为止,我设法将我的列表放入一个数组中,并且我试图通过一个函数获取我需要的项目,但在我需要它的地方,它是未定义的! 我不知道我哪里错了!!!
我想在这个控制台日志中看到结果
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')
);
最佳答案
这是因为 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]];
}
关于javascript - 通过 React js 从具有属性的项目列表中获取随机项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062074/