我不知道 Headers 是否成功,但这是我的情况:
我有一个游戏板的ParentComponent . 如果在之前的会话中用户正在播放并且由于某种原因页面重新加载或者其他什么,则存储在服务器上的移动历史以便将游戏板状态恢复到先前的会话状态 .
为了检查先前未完成的游戏,在服务器上创建/ unfinishedgames节点,其具有用户所做的第一次移动并且随每次新移动而更新 . 当游戏结束时,该节点将从服务器中删除,因此存在/未完成游戏存在的唯一方法是游戏是否已被中断 .
现在,我想在每次创建ParentComponent时检查未完成的游戏,以便提示用户是否要恢复它或启动新的 . 我在componentDidMount()中从服务器获取数据并检查/ unfinishedgame是否存在 . 如果它不存在,则表示用户已经结束了之前的每一场比赛;如果它确实存在,则意味着我需要提示用户恢复它 .
问题是if / unfinishedgame存在,在ParentComponent上 I can't find a correct place where to prompt the user for input prior to calling render() 以使用获取的信息呈现电路板 . 我的方法如下:
-
由于我在
componentDidMount()
上获取数据,使用名为{pendingGameState: response.data}
的属性调用setState()
(作为获取的待处理游戏状态的response.data)并提示用户进行回调,如果用户想要恢复游戏,则使用里面的数据更新ParentComponent状态pendingGame -
在
componentDidMount()
内部调用setState()
,使用名为{pendingGameState: response.data}
的属性然后在render()
内部声明一个名为prompt
的变量,该变量仅显示this.state.pendingGame
是否为空 .
这两种方法如下:
1 .
componentDidMount(){
axios.get(/unfinishedGames)
.then(response => {
//if response is not null
this.setState({
pendingGameState:response.data
})
}, ()=>{
// render a <UserPrompt> component to prompt the user, if user wants to resume then restore state to previous game's state
this.setState({pendingGameState})
})
}
2 .
componentDidMount(){
axios.get(/unfinishedGames)
.then(response => {
//if response is not null
this.setState({
pendingGameState:response.data
});
//Inside render
const prompt = this.state.gamePendingState ? //if true, display a <UserPrompt> that prompts for input, if user wants to resume, update state with pendingGameState.
我尝试了两种方法都有缺陷:
-
我没有得到
<UserPrompt>
渲染并显示在回调函数上(我也不知道是否可能) -
如果我采用这种方法,我将不得不在render()中调用this.setState,这是不允许的/最佳实践 .
所以我的问题是: Is there a way to render a component inside another component's class function prior to calling render() for the latter? If so, how is this possible 此外,我可以使用其他方法来实现这一目标吗?
我也尝试在方法#1的setState()回调中返回一个匿名类组件,但它也没有显示任何内容 .