【发布时间】:2019-05-01 02:29:36
【问题描述】:
这是我第一次制作有限状态自动机。我尝试制作一个停止灯类型的程序,如果您单击按钮,灯会改变一次,从绿色开始,如果再次单击则变为黄色,然后变为红色,然后再次循环。我设法使它工作,除了一个小错误。屏幕更新之前需要点击两次,我真的不知道如何修复它。
我在控制台上注意到,当我单击它时 currentLightState 会发生变化,但在第一次单击时会恢复为以前的颜色。我发现这是因为它与我的状态不同步。但是,当我尝试将 currentLightState 放入类中并分配 this.state.light 时,currentLightState 变得未定义。我尝试在 this.state.light 的末尾添加一个 .bind(this),但我只是收到另一个错误,说它不是一个函数。有什么建议吗?
我没有发布我的更新函数或我的 onHandleClick 函数,因为它不直接处理 currentLightState。
const lightMachine = {
green:{
LIGHT: 'yellow'
},
yellow:{
LIGHT: 'red'
},
red:{
LIGHT: 'green'
}
}
// current location of currentLightState
let currentLightState = 'green';
class App extends React.Component{
constructor(props){
super(props);
this.state = {
light: 'green' //initial value
};
}
transition(state, action){
// This is where my currentLightState messes up the first run
currentLightState = this.state.light
const nextLightState = lightMachine[currentLightState][action]
this.setState({light: nextLightState})
}
render(){
return(
<div>
<button onClick={this.onHandleClick.bind(this)}>
change the Light!
</button>
{currentLightState}
</div>
);
}
}
编辑:这是我的 onHandleClick 函数 :)
onHandleClick(){
this.update(currentLightState)
};
另外,我认为我只需用 this.state.light 替换渲染函数中的 currentLightState 即可解决我的问题。
Idk 如果这是否是合法的修复,但它目前似乎有效。
如果有人仍然可以回答为什么当您将 currentLightState 放入类中并将 state.light 分配给它时,它会变得未定义,那就太好了。这将有助于扩展我的 React 知识:)
【问题讨论】:
-
你能发布你的 onHandleClick 函数吗?看到这一切仍然很有用。
-
为什么在过渡函数中使用 currentLightState?为什么不直接在 lightMacing[this.state.light][action] 中直接使用 this.state.light 呢?
-
我在那里使用 currentLightState 的主要原因是因为当我看到人们使用有限状态机来制作这样的程序的其他示例时,他们都做了类似的事情。结果我认为这是正确的方法=/
-
@Jr194!欢迎来到堆栈溢出!我刚刚就您的代码以及为什么有些事情不起作用的问题给您写了一个非常详尽的答案。
标签: reactjs finite-state-automaton