更改状态后,内容不会重新呈现

时间:2020-05-06 05:42:25

标签: reactjs react-hooks state

我正在使用React钩子(钩子的新手),今天遇到了一个错误。更改状态后,内容未按原样重新呈现。这是代码:

const App = () => {
    const [messeges, UpdataMesseges] = useState([]);


    //here's the code for updating the state, but even after changing the state it's not
    //re-rendering the content on the page.
    const sendMessege = (user, messege) => {
      UpdataMesseges((prevState) => {
        prevState.push({user: user, content: messege});
        console.log(messeges); //here it logs that state is changed (previously)
        return prevState;
      });
    }

    console.log(messeges);

    return (
        <div className="App">
            <Header /> 
            <Chat>
                {
                  messeges.map(obj => <Messege content={obj.content} user="A" key={obj.content} />)
                }
            </Chat>
                {console.log(messeges)} {/*<----- Nothing gets logged even on state change*/}
            <Control>
                <Btn click={() => sendMessege('A', 'blah bla')} >blah</Btn>
            </Control>
        </div>
    );
}

export default App;

谢谢!

2 个答案:

答案 0 :(得分:3)

您正在突变现有状态对象。您必须返回新的数组对象。您可以通过将现有状态散布到新数组中并在末尾附加新对象来实现此目的。

const sendMessege = (user, messege) => {
  UpdataMesseges((prevState) => {
    return [...prevState, { user: user, content: messege }];
  });
}

如果要记录状态更新,请对要记录在依赖项数组中的状态使用效果。

useEffect(() => {
  console.log(messeges);
}, [messeges]);

答案 1 :(得分:0)

尝试

% puts $m {{bi 1/7 1/8}} {{uni 1/6}} % puts [join $m] {bi 1/7 1/8} {uni 1/6} % puts [llength [join $m]] 2 %