在React中更新useState后如何重新渲染?

时间:2019-06-20 14:27:22

标签: javascript reactjs react-hooks

我想要的是在按下按钮并刷新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;

1 个答案:

答案 0 :(得分:0)

  1. 无论何时调用setMesses(),都会自动重新渲染。要添加的一件事是,函数Send应该为小写字母,仅将组件大写而不是常规函数。

  2. 问题是您试图直接更改语句list.push()

  3. 中的数组

尝试使用此方法而不是push

let list = [...messes, {name: "", mess: document.querySelector("input").value, status:  "right"} ]
setMesses(list)