I'm rendering my only component from App.js like so:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {gameState: "Menu"};
}
render() {
return (
<div>
{<MenuCanvas/> && this.state === {gameState: "Menu"}}
</div>
)
}
}
and the Menu component looks like this
export default class MenuCanvas extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<canvas id="menu-canvas" width="800" height="800"></canvas>
</div>
)
}
componentDidUpdate() {
startMenuLogic();
}
}
startMenuLogic() function, that is called in componentDidMount is a javascript function that currently only finds the canvas that's being rendered
canvas = document.getElementById('menu-canvas');
the problem is that the canvas is null, even though the function is called in componentDidMount, and the weird part is that the canvas was not null, until I added conditional rendering with state in the App.js. Before that my App.js simple returned always, and everything was fine. What could be the problem and how could I fix this?
Your conditional rendering logic is wrong. The condition should be before the component:
{this.state === {gameState: "Menu"} && <MenuCanvas/>}
So that if the condition is false
, then <MenuCanvas/>
isn't evaluated. That's the way short circuit evaluation works:
true && expression
returns expression
, false && expression
returns false
.
Even then, as some comments have suggested already, the way you're comparing objects is not recommended since only references are compared. So your condition should be this.state.gameState === "Menu"
.
我认为你误会了双方:
{this.state.gameState === "Menu" && <MenuCanvas/>}
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.