简体   繁体   中英

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

I have this state and pass it down to 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>
    )

When I am in ChatIO and do this:

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

Everything works fine. The state is changed to ID 100283100 and react reacts to the state change.

But when I do this:

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

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

}

The function from the parent is called (i can see with the help of alerts) but react does NOT react to the state change.

How can I alter my code that react reacts (I hate saying that over and over)... to the state change when called from within a function NOT from a button click?

*** LITTLE EDIT ***

I found out that it sometimes rerenders the component and sometimes does not. So I must be doing something odd here

Whatever.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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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