@iwanglong
2018-10-26T07:09:32.000000Z
字数 1336
阅读 255
技术
出现红屏不要慌,屏幕上一般会有日志输出的,屏幕没有日志可以看终端**log,一般终端**会直接定位到报错误代码行。
bundling failed: SyntaxError: /Users/wanglong/Documents/moreWorkTest/RN/FirstProject/AppState.js: Unexpected token (7:17)
代码如下:
export default class AppStateDemo extends React.Component {
state = {
appState = AppState.CurrentState
}
componentDidMount() {
AppState.addEventListener("change", this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({ appState: nextAppState });
}
render() {
return (
<View>
<Text>Current state is :{this.state.appState}</Text>
</View>
)
}
}
报这个Unexpected token,我找了半天,原来是对象赋值出错了,
state = {
appState : AppState.CurrentState
}
这里应该用冒号,😓😓😓😓😓😓
我就想搞一个简单的点击button设置text文本的demo,没想到这么简单🌰,还让老哥我查询了半天错误原因,不说了,上代码。
constructor(props) {
super(props)
this.state = { name: '小红' }
this._onPressButton = this._onPressButton.bind(this)
}
_onPressButton() {
this.setState({ name: '小明' })
}
render() {
return (
console.log('-------render--------'),
<Button onPress={this._onPressButton} title='save' />
<Text>{this.state.name}</Text>
</View >
);
}
到底为啥出错了呢,点击事件里面setState时会使this重新定义,所以在点击的函数里面使用this.setState()时会报错this.setState not a function,因此需要提前给点击事件的函数绑定this