[英]react native bind this undefined function
I am trying to set state after socket on function but 我试图在功能启用套接字后设置状态,但是
componentWillMount() {
socket.on('foo', function(msg){
//alert(JSON.stringify(msg));
//this.setState({user:msg});
this.setState({veri:msg});
this.setState({initial:msg});
});
undefined is not a function (evaluating 'this.setState({ veri: msg })') index.android.js:95:14 emit index.js:133:25 onevent socket.js:270:15 onpacket socket.js:228:19 index.js:21:20 emit index.js:133:25 ondecoded manager.js:345:12 index.js:21:20 emit index.js:133:25 add index.js:241:16 ondata manager.js:335:19 index.js:21:20 emit index.js:133:25 onPacket socket.js:457:18 socket.js:274:18 emit index.js:133:25 onPacket transport.js:145:12 onData transport.js:137:16 onmessage websocket.js:147:16 dispatchEvent event-target.js:172:43 WebSocket.js:148:27 emit EventEmitter.js:182:12 __callFunction MessageQueue.js:250:47 MessageQueue.js:101:26 __guard MessageQueue.js:218:6 callFunctionReturnFlushedQueue MessageQueue.js:100:17
undefined不是一个函数(评估'this.setState({veri:msg})')index.android.js:95:14发出index.js:133:25 onevent socket.js:270:15 onpacket socket.js: 228:19 index.js:21:20发出index.js:133:25 on解码管理器.js:345:12 index.js:21:20发出index.js:133:25添加index.js:241:16 ondata manager.js:335:19 index.js:21:20发出index.js:133:25 onPacket socket.js:457:18 socket.js:274:18发出index.js:133:25 onPacket transport.js: 145:12 onData transport.js:137:16 onmessage websocket.js:147:16 dispatchEvent event-target.js:172:43 WebSocket.js:148:27发出EventEmitter.js:182:12 __callFunction MessageQueue.js:250 :47 MessageQueue.js:101:26 __guard MessageQueue.js:218:6 callFunctionReturnFlushedQueue MessageQueue.js:100:17
While it's not possible to tell conclusively from the small chunk of code you provided, it's likely that this
inside of socket.on
is referring to the socket, not React. 虽然它不能从您所提供的代码小块决定性地告诉,很可能是
this
里面socket.on
是指插座,还没有反应过来。
You could either try using an arrow function: 您可以尝试使用箭头功能:
socket.on('foo', msg => {
this.setState({veri:msg});
this.setState({initial:msg});
});
You could also set this
to something (like self
) before calling socket
, then use self
instead of this
inside: 您还可以设置
this
东西(如self
调用之前) socket
,然后用self
的,而不是this
里面:
const self = this;
socket.on('foo', function(msg){
this.setState({veri:msg});
this.setState({initial:msg});
});
You could also define the function outside the handler, and bind it to this
: 您也可以在处理程序外部定义函数,并将其绑定
this
:
const handleFoo = (function(msg){
this.setState({veri:msg});
this.setState({initial:msg});
}).bind(this);
socket.on('foo', handleFoo);
All three of those are ways to keep this
what you expect and not let it change inside of another context. 所有这三个是如何保持
this
你所期望的,而不是让它另一个上下文内改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.