反应-输入状态到列表状态

时间:2020-02-10 13:12:59

标签: javascript reactjs chat

我正在尝试聊天应用。我的目标是,当用户提交输入时,将其添加到{messages}状态,然后映射消息。消息是空白列表。我必须获取用户的输入,然后将其添加到消息中。但是我不明白它是如何工作的。

进口

import React, { useEffect, Component, useState, setState } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";

聊天

const Chat = ({ value, suggestions, auth: { user } }) => {
  const [formData, setFormData] = useState({
    input: ""
  });

  const { input } = formData;

返回

  return (
    <div>
      <div>
        <a>
          {messages.map((item, i) => (
            <li key={i}>Test</li>
          ))}
        </a>
        <br />
        <div>
          <div className="App"></div>
        </div>
      </div>
      <br />
      <form noValidate onSubmit={e => onSubmit(e)}>
        <div>
          <input />
          <div>
            <button>
              <a>Send</a>
            </button>
          </div>
        </div>
      </form>
    </div>
  );
};

PropTypes,mapStateToProps并导出

Chat.propTypes = {
  getCurrentName: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps, { getCurrentName })(Chat);

1 个答案:

答案 0 :(得分:0)

请勿在功能组件中使用this。正确的代码应如下所示:

const Chat = ({ value, suggestions, auth: { user } }) => {
  const [formData, setFormData] = useState("");

  const [messages, setMessages] = useState([]);

  const onChange = e =>
    setFormData(e.target.value);

  const onSubmit = event => {
    event.preventDefault();
    setMessages(prevMsgs => [...prevMsgs, formData]);