【问题标题】:react - this = undefined, how to pass the prop into my function反应 - this = undefined,如何将道具传递给我的函数
【发布时间】:2020-12-04 16:03:01
【问题描述】:

我已将我的用户 ID 传递到我的“OrderMessages”组件中,但在我的函数中显示未定义。当我的用户使用 handleFormSubmit 函数中的表单提交消息时,我需要用户 ID 和消息的日期时间。我已经设法获取日期和时间,但是在尝试控制台日志以获取用户 ID 时,我不断收到错误消息。我已经尝试过 this.props .... 和 this.state 但都说未定义,请您帮忙。在我的构造函数中,我使用 const UserId = props.location.state.UserID; 进行了测试在调试中我可以看到这已经正确获得了 UserID,所以我不确定如何将它放入我的 hadleFormSubmit 函数中。

import React from "react";
import Moment from "moment";
import { Form, Button } from "react-bootstrap";

class OrderMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoading: false,
      checkboxes: [],
      selectedId: [],
      formLableSelected: "",
      formSelectedSubject: "",
      formSelectedSubjectId: "",
      formNewSubject: "",
      formChainID: "",
      formMessageBody: "",
      userId: '',
    };
    const UserId = props.location.state.UserID;
  }
  

  componentDidMount() {
    this.setState({ isLoading: true });
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    const url =
      "myURL" +
      this.props.location.state.orderNumber;
    fetch(proxyurl + url)
      .then((res) => res.json())
      .then((data) => this.setState({ data: data, isLoading: false }));
  }

  handleClick = (id) => {
    if (this.state.selectedId !== id) {
      this.setState({ selectedId: id });
    } else {
      this.setState({ selectedId: null });
    }
  };

  setformSubjectID(messageSubject) {
    if (messageSubject.subject === this.state.formSelectedSubject) {
      this.setState({ formSelectedSubjectId: messageSubject.messageSubjectId });
    }
  }

  handleChangeSubject = (event) => {
    this.setState({ formSelectedSubject: event.target.value });
    this.state.data.message_Subjects.map((ms) => this.setformSubjectID(ms));
  };

  handleFormSubmit(e) {
    e.preventDefault();

    // get current time
    let submit_time = Moment().format("ddd DD MMM YYYY HH:mm:ss");
    console.log("messageDatetime", submit_time);

    // get user id  THIS IS WHAT DOESN’T WORK
    console.log("messageSentFrom", this.state.userId);
console.log("messageSentFrom", this.props.location.state.UserID);

  }

  render() {
    const { data, isLoading } = this.state;

    if (isLoading) {
      return <p>Loading ...</p>;
    }

    if (data.length === 0) {
      return <p> no data found</p>;
    }

    console.log("mess: ", data);

    return (
      <div>
        
        <div className="sendMessageContent">
         <Form className="sendMessageForm" onSubmit={this.handleFormSubmit}>
            <Form.Group className="formRadio">
              <Form.Check
                className="formRadiob"
                type="radio"
                label="New chat"
                value="new"
                name="neworexisitng"
                id="New Message"
                onChange={this.onFormMessageChanged}
                defaultChecked
              />
              <Form.Check
                className="formRadiob"
                type="radio"
                label="Reply to exisiting chat"
                value="reply"
                name="neworexisitng"
                id="exisiting Message"
                onChange={this.onFormMessageChanged}
              />
            </Form.Group>
            {this.returnCorrectFormFields(data)}
            <Form.Group>
              <Form.Label>Message Body</Form.Label>
              <Form.Control as="textarea" rows={3} />
            </Form.Group>
            <Button variant="primary" type="submit">
              Send Message
            </Button>
          </Form>
        </div>
      </div>
    );
  }

 returnCorrectFormFields(data) {
    if (this.state.formLableSelected === "new") {
      return this.newMessageSubject(data);
    } else {
      return this.choseMessageSubject(data);
    }
  }

  choseMessageSubject(data) {
    return (
      <Form.Group>
        <Form.Label>Select the message subject</Form.Label>
        <Form.Control as="select" onChange={this.handleChangeSubject}>
          <option value="0">Choose...</option>
          {data.message_Subjects.map((ms) => (
            <option value={ms.subject}>{ms.subject}</option>
          ))}
        </Form.Control>
      </Form.Group>
    );
  }

  newMessageSubject(data) {
    return (
      <Form.Group>
        <Form.Label>Enter Message Subject</Form.Label>
        <Form.Control type="text" placeholder="Enter message subject" />
      </Form.Group>
    );
  }

  onFormMessageChanged = (event) => {
    this.setState({
      formLableSelected: event.target.value,
    });
  };

  getAllMessageInChain(messageChain) {
    return (
      <div className="messageHistory">
        <div className="messageHistoryHeader">
          <div className="innerMS-history-body">Message</div>
          <div className="innerMS">Date and Time</div>
          <div className="innerMS">Message sent by</div>
        </div>
        {messageChain.map((ms) => (
          <div className="messageHistoryBody">
            <div className="innerMS-history-body">{ms.messageBody}</div>
            <div className="innerMS">
              {Moment(ms.dateTime).format("ddd DD MMM YYYY hh:mm:ss")}
            </div>
            <div className="innerMS">{ms.sentFromId}</div>
          </div>
        ))}
      </div>
    );
  }

  getLatestMessageDateTime(messageChain) {
    const lastmessage = messageChain.length - 1;

    Moment.locale("en");
    var dt = messageChain[lastmessage].dateTime;
    return Moment(dt).format("ddd DD MMM YYYY hh:mm:ss");
  }
}

export default OrderMessages;

【问题讨论】:

  • 把这个扔到render()函数中:const UserId = props.location.state.UserID;

标签: reactjs state react-props


【解决方案1】:

this 的范围不是您正在使用的函数中的组件。

handleFormSubmit 更改为此以自动绑定this

handleFormSubmit = (e) => {
  // .. your code
}

或在构造函数中手动绑定this

constructor() {
  // ..other code
  this.handleFormSubmit = this.handleFormSubmit.bind(this)
}

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 2022-01-22
    • 2016-12-11
    • 2018-04-09
    • 1970-01-01
    • 2019-07-29
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多