我想要的是在按下按钮并刷新useState
之后,我想刷新内容。
这是我的代码:
import React, {useState, useEffect} from 'react';
import MessComponents from './messConatiner';
function Conatiner() {
const [messes, setMesses] = useState([
{name: "Chater1: ", mess: "Hi", status: "left"},
{name: "", mess: "Hi!", status: "right"},
{name: "Chater2: ", mess: "I have some trouble with react...", status: "left"}
]);
function Send(){
let list = messes;
list.push({name: "", mess: document.querySelector("input").value, status: "right"});
setMesses(list);
console.log(messes);
}
return (
<div className="container" id="cont">
<MessComponents messes={messes}/>
<input className="chat-input" type="text" />
<button onClick={Send}>Send</button>
</div>
);
}
export default Conatiner;
答案 0 :(得分:0)
无论何时调用setMesses(),都会自动重新渲染。要添加的一件事是,函数Send应该为小写字母,仅将组件大写而不是常规函数。
问题是您试图直接更改语句list.push()
尝试使用此方法而不是push
let list = [...messes, {name: "", mess: document.querySelector("input").value, status: "right"} ]
setMesses(list)