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



我正在尝试做聊天应用程序。我的目标是,当用户提交输入时,将其添加到{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>
);
};

PropType, mapStateToProps 和 Export

Chat.propTypes = {
getCurrentName: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps, { getCurrentName })(Chat);

您不会在功能组件中使用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]);

相关内容

  • 没有找到相关文章

最新更新