繁体   English   中英

react.js 状态函数仅在从按钮而不是从函数调用时对 statechange 做出反应

[英]react.js state function only reacts to statechange when called from button but not from function

我有这个状态并将它传递给 ChatIO

var [chatRoomIDs, setIDofRoom ] = React.useState(0); 

const changeChatRoomID = (id) => {
    setIDofRoom(chatRoomIDs = id); // write new state to state name. this function can be handed down to any component 
}

    return (
        <div className="container">
            <ChatIO chatroomID={chatRoomIDs} chatRoomFunction={changeChatRoomID}/>
        </div>
    )

当我在 ChatIO 中并执行以下操作时:

        <Button onClick={() => props.chatRoomFunction(100283100)}variant="contained">senden</Button>

一切正常。 状态更改为 ID 100283100 并对状态更改做出反应。

但是当我这样做时:

                <Button onClick={() => buttonClick()}variant="contained">senden</Button>

function buttonClick() {
    SendMessage()
    props.chatRoomFunction(100283100)

}

来自父级的函数被调用(我可以在警报的帮助下看到)但 react 不会对状态变化做出反应。

我怎样才能改变我的反应代码(我讨厌一遍又一遍地说)...当从函数内部调用而不是从按钮单击调用时状态更改?

*** 小编辑 ***

我发现它有时会重新渲染组件,有时不会。 所以我一定在这里做了一些奇怪的事情

随便.js

var [chatRoomIDs, setIDofRoom ] = React.useState(0); 

return (
  <div className="container">
    <ChatIO chatroomID={chatRoomIDs} chatRoomFunction={setIDofRoom}/>
  </div>
)

ChatIO.js

const ChatIO = (props) => {
  function changeChatRoomId(id) {
    // sendMessage()
    // props.chatRoomFunction(100283100)  
    
    // but you probably want that 
    props.chatRoomFunction(id)
  }

  return (
    <Button onClick={() => changeChatRoomId(100283100`enter code here`)}variant="contained">senden</Button>
  )
}

暂无
暂无

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

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