react-native this.setState 导致代码停止运行
Posted
技术标签:
【中文标题】react-native this.setState 导致代码停止运行【英文标题】:react-native this.setState causing code to stop running 【发布时间】:2019-09-27 14:28:40 【问题描述】:我有一个 websocket 连接设置,react-native 成功连接到该连接。我的代码如下:
export default class Settings extends React.PureComponent
constructor()
super()
this.state =
questionText: ''
connect()
console.log('connected');
var socket = new WebSocket('ws://127.0.0.1:8000/users/');
socket.onopen = function open()
console.log('WebSockets connection created.');
socket.onmessage = function message(event)
var data = JSON.parse(event.data);
var username = encodeURI(data['username']);
var question = encodeURI(data['question']);
console.log('username: ' + username);
console.log('question: ' + question);
this.setState( questionText: question );
console.log('state: ' + this.state.questionText);
render()
return (
<View style=styles.container>
<Text>this.state.questionText</Text>
<Button
title = "Connect"
onPress = this.connect />
</View>
);
const styles = StyleSheet.create(
container:
backgroundColor: '#EFEFF4',
alignItems: 'center',
justifyContent: 'center',
flex: 1,
,
);
当从后端发送消息并且用户名和问题按预期打印到控制台时,将调用 on message 函数。但是状态没有改变,我在this.setState( questionText: question );
之后放置的任何代码也没有运行
该行似乎引起了一些问题,但是控制台没有打印错误。我相信一旦状态发生变化,我正在渲染的 Text 组件也会发生变化。
【问题讨论】:
【参考方案1】:尝试将您的函数转换为箭头函数。 this.setState
可能在您设置的上下文中未定义。将函数更改为箭头函数允许 this
在词法范围内。
...
connect = () =>
console.log('connected');
var socket = new WebSocket('ws://127.0.0.1:8000/users/');
socket.onopen = function open()
console.log('WebSockets connection created.');
socket.onmessage = (event) =>
var data = JSON.parse(event.data);
var username = encodeURI(data['username']);
var question = encodeURI(data['question']);
console.log('username: ' + username);
console.log('question: ' + question);
this.setState( questionText: question );
console.log('state: ' + this.state.questionText);
...
如果你不想使用箭头函数,那么你也可以使用.bind
来确保this
是正确的。
export default class Settings extends React.PureComponent
constructor()
super()
this.state =
questionText: ''
this.connect.bind(this);
connect()
console.log('connected');
var socket = new WebSocket('ws://127.0.0.1:8000/users/');
socket.onopen = function open()
console.log('WebSockets connection created.');
socket.onmessage = function message(event)
var data = JSON.parse(event.data);
var username = encodeURI(data['username']);
var question = encodeURI(data['question']);
console.log('username: ' + username);
console.log('question: ' + question);
this.setState( questionText: question );
console.log('state: ' + this.state.questionText);
.bind(this)
...
【讨论】:
以上是关于react-native this.setState 导致代码停止运行的主要内容,如果未能解决你的问题,请参考以下文章
react-native init 指定 react 版本和 react-native 版本