簡體   English   中英

反應 - 這 = 未定義,如何將道具傳遞到我的 function

[英]react - this = undefined, how to pass the prop into my function

我已將我的用戶 ID 傳遞到我的“OrderMessages”組件中,但在我的 function 中顯示未定義。 當我的用戶使用 handleFormSubmit function 中的表單提交消息時,我需要用戶 ID 和消息的日期時間。 我已經設法獲取日期和時間,但是在嘗試控制台日志以獲取用戶 ID 時,我不斷收到錯誤消息。 我已經嘗試過 this.props.... 和 this.state 但都說未定義,請您幫忙。 在我的構造函數中,我使用 const UserId = props.location.state.UserID; 進行了測試在調試中我可以看到這已經正確獲得了用戶 ID,所以我不確定如何將它放入我的 hadleFormSubmit function。

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;

this不是您正在使用的 function 中的組件。

handleFormSubmit更改為 this 以自動綁定this

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

或在構造函數中手動綁定this

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM