这很难用词组成,但我想获取存储在对象中的函数的返回值,将该值添加到数组并输出。我已经完成了这一切,但是一旦再次运行它就不会改变,所以说它输出随机数678它下次也将输出相同的数字,依此类推。我在react中创建了这个很酷的终端,如果它存在则获取密钥的命令,并通过返回jsx将其输出到我的控制台中。
这是我的文件结构......
这是我的反应代码...(我遇到格式问题,here是下面代码的更好版本)
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import "./Main.css";
import Commands from "../Commands/Commands.js"
class Main extends Component {
constructor(props){
super(props);
this.state = {inputValue: ''}
this.outputs = ["type 'help' for information about plunketTheTerminal"];
this.commands = Commands;
this.commands.keys = Object.keys(this.commands)
}
handleSubmit = (event) => {
if(event.key == "Enter") {
if( this.state.inputValue != "" ) {
if( this.commands.keys.includes(this.state.inputValue)) {
this.outputs.unshift(this.commands[this.state.inputValue]);
}
else{
this.outputs.unshift(`No command '${this.state.inputValue}' found.`)
}
}
document.querySelector(".input-section").value = "";
}
this.forceUpdate()
}
handleChange = (e) => {
this.setState({ inputValue: e.target.value })
}
render() {
return(
<div>
<div className="terminal-header"></div>
<div className="terminal-body">
<div className="terminal-contents-wrapper">
<div className="output-item-wrapper">
{
this.outputs.map((output, index) => {
return <h1 className="output-item" key={ index }>{output}</h1>;
})
}
</div>
<div className="input-section-wrapper">
<input type="text" className="input-section" onKeyPress={this.handleSubmit} onChange={this.handleChange}/>
<span className="input-section-label">plunketTheTerminal@plunketTheTerminal-H170-D3H:~$</span>
</div>
</div>
</div>
</div>
)
}
};
export default Main;
最后我的命令的JavaScript文件......(再次更好的代码here)
const rand = () => {
return Math.floor(Math.random() * 1000 ) + 1;
}
const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can actually SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: rand(),
"rand --info": "Will generate a random number between 1 and 1000",
}
export default Commands
编辑:尝试使用以下任何一项都不会返回任何内容。
rand: () => (
"x"
),
或
rand: () => {
return "x"
},
以下是对正在发生的事情的演示......
但是从那时起重复相同的命令不会生成新的随机数,我将继续重复第一个返回的值。
我真的很感激一些帮助,但请记住,我仍在学习反应和JavaScript,并希望听到任何建设性的反馈。如有需要,我还会继续更新信息。谢谢!
答案 0 :(得分:0)
发现错误,我在没有括号的情况下调用函数。我不得不将命令文件更改为以下内容......
const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: () => {
return Math.floor(Math.random() * 1000 ) + 1;
},
//"rand --info": "Will generate a random number between 1 and 1000",
}
我不得不改变这条线
this.outputs.unshift(this.commands[this.state.inputValue]);
到
this.outputs.unshift(this.commands[this.state.inputValue]());
愚蠢的错误,希望这可以帮助那些有类似问题的人,虽然我认为这不太可能。