我有用Reactjs和Redux编写的应用程序。使用axios可以很好地工作,但是我想使用socket.io,因此在redux动作中尝试:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Content-Type: images/jpeg');
include_once '../../config/Database.php';
include_once '../../models/Post2.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate post object
$post = new Post2($db);
// post query
$result = $post->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if ($num > 0) {
// Post array
// $posts_arr = array();
$posts_arr['data'] = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$post_item = array(
'id' => $id,
'pic' => $pic,
'name' => $name,
'address' => $address,
'type' => $type,
);
// Push to "data"
//array_push($posts_arr, $post_item);
array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
如果我第一次调用此操作,一切正常-发出套接字,函数返回正确的msg,console.log返回“测试”,但是如果再次调用此函数,则console.log称为一个(可以),但是不幸的是,“ socket.on”被调用了两次。接下来,如果我单击,则“ socket.on”函数将被调用三次,等等。
何时应该放置函数export const getOne = (id) => async dispatch => {
socket.emit('getOne', id);
console.log('test');
socket.on('get', function(msg) {
console.log(msg);
dispatch({ type: GET, payload: msg });
});
};
?或者该怎么办?
答案 0 :(得分:0)
您需要将“ socket.on”移至功能失效。每次调用此函数时,它都会一次又一次地绑定:
socket.on('get', function(msg) {
console.log(msg);
dispatch({ type: GET, payload: msg });
});
export const getOne = (id) => async dispatch => {
socket.emit('getOne', id);
console.log('test');
};