我有以下的senario,我希望在React中将一个布尔值发送回我的组件。我可以在server.js中发出并调用我的方法,但是我无法弄清楚如何在执行后发回数据。
Server.js:
...
const io = require('socket.io')(server);
var fetch = () => {
url = 'abc';
request(url, function(error, response, html){
...
fs.writeFile(__dirname + '/data/output.json', JSON.stringify(result, null, 4), function(err){
if(err) {
throw err;
} else {
console.log('File successfully written! - Check your project directory for the output.json file');
io.on('connection', (socket) => {
console.log('send data back to component');
});
}
});
})
}
io.on('connection', (socket) => {
//console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('fetchData', () => {
fetch();
});
});
Component.js(反应)
...
handleClick() {
socket.emit('fetchData');
}
render() {
return (
<div>
<button onClick={(e) => this.handleClick(e)}>Fetch</button>
</div>
)
}
答案 0 :(得分:2)
首先,在您的fetch()
功能中,您再次收听了您的连接。其次,我认为你需要在你的组件上添加一个监听器。 e.g。
Server.js:
var fetch = (socket) => {
url = 'abc';
request(url, function(error, response, html){
...
fs.writeFile(__dirname + '/data/output.json', JSON.stringify(result, null, 4), function(err){
if(err) {
throw err;
} else {
console.log('File successfully written! - Check your project directory for the output.json file');
var bool;
socket.emit('get-data-back', bool);
}
});
})
}
io.on('connection', (socket) => {
//console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('fetchData', () => {
fetch(socket);
});
});
组件:
...
componentDidMount() {
socket.on('get-data-back', (data) => {
console.log(data);
})
}
handleClick() {
socket.emit('fetchData');
}
render() {
return (
<div>
<button onClick={(e) => this.handleClick(e)}>Fetch</button>
</div>
)
}