问题描述
我试图从三元组有条件地调用一个函数,但是它似乎在我想要它之前调用了该函数......
我知道通常我可以通过执行 () => myFunc()
来解决这个问题,但是这似乎不起作用并且破坏了我的构建。
const myFunc = () => {
if (typeof someVar === 'boolean') {
if (someVar) {
return <h1>BOOLEAN - TRUE</h1>
} else {
return <Redirect to={`/my-page`} />
}
} else {
return <h1>not boolean</h1>
}
}
return !somethingLoaded
? <h1>not loaded yet</h1>
: !extraThingLoaded
? <h1>Not quite finished</h1>
: myFunc()
按原样运行此代码,会在执行任何操作之前调用 <Redirect>
。
我确实尝试过
!extraThingLoaded
? <h1>Not quite finished</h1>
: () => myFunc() // <-- Added this that usually works...
但是我收到错误:Functions are not valid as a React child
也在尝试:
!extraThingLoaded
? <h1>Not quite finished</h1>
: {myFunc()}
解决方法
const renderThings = ()=>{
if(somethingLoaded && extraThingLoaded){
x();
}else if(!somethingLoaded){
return <h1>not loaded yet</h1>
}else if(!extraThingLoaded){
return <h1>Not quite finished</h1>
}
}
return (<div>{renderThings()}</div>)