我是在reactjs中使用状态的初学者,如果我的问题不应该在正确的位置提出,我很抱歉.Using React js, Node js and mongodb
因此,我创建了一个构造函数,并在其中初始化了一个名为val的变量,然后在textarea标记中的value属性中传递该变量,这样用户就可以输入一些东西,并将其保存在val变量中(我不确定这样做是否正确,所以我问!).此外,我创建了一个名为handleSubmit的函数,该函数将获取变量val并将其保存在mongodb中,我在用户传入某个东西时应该单击的按钮中调用了该函数.但这一切似乎都不适合我.
这是我的平.js文件:
class Pingbutton extends React.Component {
constructor(props) {
super(props);
this.state = { val: "Ford" };
}
handleSubmit = () => {
// if we get state error then we need to put it in a claa and call the constructot and then call the function using this.state.the name of the function
console.log("its running 1");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + databody.message);
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: JSON.stringify(databody),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
render() {
return (
<div className="ok2">
<textarea
className="message"
type="text"
placeholder="Write me somthing!. Also, double click to ping:) "
value={this.setState.val}
></textarea>
<button
className="button"
onClick={() => {
this.magic();
this.handleSubmit(); //animation + //pinging the phone
// this.handleButtonClick(); //setVal(() => ""); //sets the value of the box to empty
}}
>
</button>
</div>
);
}
}
export default Pingbutton;
这是后端(nodejs)索引.js文件:
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
connectDB();
app.use(cors({ origin: "http://localhost:3000" }));
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.use(cors({ origin: "http://localhost:3000" }));
app.get("/Pinged", function (req, res) {
find_my_iphone("omar.fsm98@gmail.com", "Faresomar123", "Omar");
res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});
app.use(cors({ origin: "http://localhost:3000" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection("quotes").insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
在框中键入somthing并单击按钮(执行handleSubmit)功能)后,我一直在前端的双控制台中使用Ford.我试过这样做.状态val,但不起作用,然后我把它改成了这个.设置状态.val和也不起作用.
我会很感激你的帮助.
谢谢您!