简体   繁体   English

React - 输入状态以列出状态

[英]React - Input state to list state

I am trying to do chat app.我正在尝试做聊天应用程序。 My goal is, when user submits an input, add it to {messages} state then map the messages.我的目标是,当用户提交输入时,将其添加到 {messages} 状态然后映射消息。 messages is a blank list.消息是一个空白列表。 I must get user's input then add it to messages.我必须获得用户的输入,然后将其添加到消息中。 But I don't understand how it works.但我不明白它是如何工作的。

Imports进口

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

Chat聊天

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

  const { input } = formData;

Return返回

  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 and export PropTypes、mapStateToProps 和导出

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

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

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

You don't use this in a functional component.您不在功能组件中使用this Correct code should look like 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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM