我是在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和也不起作用.

我会很感激你的帮助.

谢谢您!

推荐答案

解决方法是创建一个函数,该函数可以执行以下所有操作:

class App extends React.Component {
  constructor() {
    super();
    this.state = {header: 'yeaheheh'};
  }
  changeHeader = (e) => {
     e.preventDefault();
    let newHeader = this.textInput.value;
    console.log('submitted');
    this.setState({header : newHeader});
  }
  render() {
    return (
      <div>
            <h1>{this.state.header}</h1>
            <form onSubmit={this.changeHeader} className="change-header-form">
                <input id="input" ref={(input) => { this.textInput = input; }} type="text" placeholder="Enter Text Here" />
                <input type="submit" value="Submit" />
            </form>
          </div>  
    );
  }
}

ReactDOM.render(<App />, document.getElementById('test'));

完整答案可在该链接中找到:Change a state in react

Javascript相关问答推荐

防止用户在selectizeInput中取消 Select 选项

Redux查询多个数据库Api reducerPath&

如何在Connect 4游戏中 for each 玩家使用位板寻找7形状?

扫描qr code后出错whatter—web.js

使搜索栏更改语言

浮动Div的淡出模糊效果

在观察框架中搜索CSV数据

如何将Cookie从服务器发送到用户浏览器

S文本内容和值不必要的不同

使用原型判断对象是否为类的实例

如何在使用rhandsontable生成表时扩展数字输入验证?

环境值在.js文件/Next.js中不起作用

使用getBorbingClientRect()更改绝对元素位置

Node.js API-queryAll()中的MarkLogic数据移动

如何根据查询结果重新排列日期

更改agGRID/Reaction中的单元格格式

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

ComponentWillReceiveProps仍在React 18.2.0中工作

如何在加载页面时使锚定标记成为焦点

响应,Use Callback更新状态变量,该变量也存在于其依赖数组中,它如何防止无限重新呈现?