小编iRo*_*tia的帖子

导航到不同屏幕时如何断开套接字

我正在使用socket.io-client来获取加密货币的最新数据

constructor() {
    super();
      this.socket = openSocket('https://coincap.io');
    }
Run Code Online (Sandbox Code Playgroud)

然后调用它componentDidMount

 componentDidMount() {
    this.socket.on('trades', (tradeMsg) => {
          for (let i=0; i< this.updateCoinData.length; i++) {
             console.log("it is being called still")
              if (this.updateCoinData[i]["short"] == tradeMsg.coin ) {
                  this.updateCoinData[i]["price"] = tradeMsg["message"]['msg']['price']
                  //Update the crypto Value state in Redux
                  this.props.updateCrypto(this.updateCoinData);
              }
          }
      })
Run Code Online (Sandbox Code Playgroud)

由于套接字已打开,因此它将继续发出消息。现在我想当我从一个屏幕导航到另一个屏幕时,套接字连接将断开,因此我正在做这样的事情

componentWillUnmount() {
 this.socket.disconnect();
}
Run Code Online (Sandbox Code Playgroud)

但即使我已经导航到不同的页面,我的套接字仍在继续发出信号,这意味着它仍然处于连接状态。

我不确定这是否是因为react-navigation我在这里使用StackNavigator

这是我的react-navigation组件

export const MyScreen = createStackNavigator({
  Home: { 
    screen: CoinCap
  },
  CoinCapCharts: {
     screen: CoinCapCharts
    },
  CurrencySelection: {
    screen: …
Run Code Online (Sandbox Code Playgroud)

sockets reactjs react-native

5
推荐指数
1
解决办法
7424
查看次数

Passport策略如何在场景后面工作

我试图了解护照策略是如何运作的.

考虑我用于验证的这些api路由.

  router.get("/google",  passport.authenticate('google', { scope: ['profile', 'email'] }));
  router.get("/google/callback", passport.authenticate('google'), (req, res) => {
      res.redirect("http://localhost:3000/")
  })
Run Code Online (Sandbox Code Playgroud)

这是护照策略

const passport = require('passport')
const GoogleStratergy = require('passport-google-oauth20')
const keys = require("./key.js")
const User = require("../models/user-model.js")

passport.serializeUser((user, done) => {
    done(null, user.id) 
})

passport.deserializeUser((id, done) => {
    User.findById(id).then((user) => {
        done(null, user) //pass it in req of our routes
    })
})

passport.use(
    new GoogleStratergy({
    //Options for the stratergy 
        callbackURL: "/auth/google/callback", 
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret
    }, (accessToken, refreshToken, profile, done) => {


        User.findOne({userId: …
Run Code Online (Sandbox Code Playgroud)

node.js passport.js

5
推荐指数
0
解决办法
169
查看次数

Firebase - 类型错误:路径必须是字符串。收到未定义

我刚刚开始使用firebase。

我不确定firebase的来龙去脉,根据我模糊的理解,我已经这样配置了我的应用程序。

在主Index.js文件中,我需要

const path = require('path')
const firebaseConfig = require("./src/config/firebaseConfig.js")
const firebaseDb = require("./src/helperFunctions/firebase_db.js")
Run Code Online (Sandbox Code Playgroud)

在这里,firebaseConfig 是我配置我的 firebase 的地方

const firebaseConfigJSON = require("./functions-config.json")
const admin = require("firebase-admin");


admin.initializeApp({
    credential: admin.credential.cert(firebaseConfigJSON),
    databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})

const db =  admin.firestore()
db.settings({ timestampsInSnapshots: true });

 module.exports = {
    db
 }
Run Code Online (Sandbox Code Playgroud)

然后使用这个导入的数据库 firebaseDb

//All the operations at firebase store would be done from here 
const firebaseDb = require("./../config/firebaseConfig.js")

    firebaseDb.db.collection('users').add({
        name: "Rohit Bhatia",
        age: "24"
    })
    .then((response) => {
        console.log("this is response", response)
    }) …
Run Code Online (Sandbox Code Playgroud)

node.js express firebase

5
推荐指数
1
解决办法
2348
查看次数

如何在功能组件中访问DOM

我在 reactJS 中创建了一个速度计并使用了一些普通的语法,但是画布返回了 null。如果我跑

const canvas = document.getElementById('dial__container');
Run Code Online (Sandbox Code Playgroud)

在控制台中,div 立即弹出。

这仅仅是画布尚未呈现的时间问题还是一些奇怪的 React 行为?

import React from 'react';

const canvas = document.getElementById('dial__container');
const ctx = canvas.getContext('2d');
const radius = canvas.height / 2;

const Speedometer = (props: any) => {

 console.log(canvas); // null
 return (
       <div className="dial__wrapper">
          <canvas id="dial__container" width="150" height="150" />
       </div>
    );
 };

export default Speedometer;
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

5
推荐指数
1
解决办法
4152
查看次数

ER_ACCESS_DENIED_ERROR CloudSQL

我收到一个如下所示的错误(在我的函数日志中)

用户访问被拒绝\'varun_admin\'@\'cloudsqlproxy~84.117.112.32\' (using password: YES)',

    sqlMessage:
`\'varun_admin\'@\'cloudsqlproxy~84.117.112.32\' (using password: YES)',`
    sqlState: '28000',
 
Run Code Online (Sandbox Code Playgroud)

fatal: true } ( 84.117.112.32) 有意修改。

我仔细检查了我usernamepassword,事实上,我从工作台提出了请求,一切顺利。

这就是我创建/初始化 sql 的方式

const mysql = require('mysql')
const config = require('./../../config.js')


const connectionName = config.DB_CONNECTION_NAME
console.log(`Connection name: ${config.DB_CONNECTION_NAME}`)
const configSQL = {
    host: config.DB_HOST,
    user: config.DB_USER,
    password: config.DB_PASSWORD,
    database: config.DB_DATABASE
}

// Connection to cloud sql in production

if (!process.env.dev) {
    configSQL.socketPath = `/cloudsql/${connectionName}`;
}

//SQL Config
const pool = mysql.createPool(configSQL)

// Checking if it …
Run Code Online (Sandbox Code Playgroud)

javascript mysql google-cloud-sql firebase google-cloud-functions

5
推荐指数
2
解决办法
1552
查看次数

React-profiler:元素类型无效

基于React Docs这篇媒体文章,我做了一些像这样简单的事情来尝试在 React 中使用分析器

import React, { unstable_Profiler as Profiler }  from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component {

   logProfile = (id, phase, actualTime, baseTime, startTime, commitTime) => {
    console.log(`${id}'s ${phase} phase:`);
    console.log(`Actual time: ${actualTime}`);
    console.log(`Base time: ${baseTime}`);
    console.log(`Start time: ${startTime}`);
    console.log(`Commit time: ${commitTime}`);
};

render () {
  return (
    <div>
      <Profiler id="app" onRender={this.logProfile}>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p> …
Run Code Online (Sandbox Code Playgroud)

reactjs

5
推荐指数
1
解决办法
537
查看次数

将 componentDidMount 替换为 useEffect

我正在浏览 React Hooks 文档,它提到

\n\n
\n

如果您熟悉 React 类生命周期方法,您可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。

\n
\n\n

假设我现在有一个类组件,在 componentDidMount 中我正在做这样的事情

\n\n
  componentDidMount() {\n    MapboxGL.setTelemetryEnabled(false);\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

据我记得,组件安装在生命周期中只调用一次?

\n\n

如果我要使用反应钩子那么它会是这样的

\n\n
  useEffect(() => {\n   MapboxGL.setTelemetryEnabled(false);\n  });\n
Run Code Online (Sandbox Code Playgroud)\n\n

每次反应功能钩子组件中的状态发生变化时,这都会调用我的函数吗?打电话不是多余吗 MapboxGL.setTelemetryEnabled(false);?当您只想在组件安装后执行此操作时?

\n\n

React 文档已经展示了如何useEffect如何替换多个生命周期方法,但我仍然无法理解 React hooks 如何替换 componentDidMount?

\n\n

另外,只是一个旁注问题,你能使用钩子制作一个完整的应用程序(比如 foursquare 或 instagram 吗?)

\n

reactjs

5
推荐指数
1
解决办法
9665
查看次数

在 React hooks 中传递状态与使用上下文

我通过观看这个视频来探索 useContext React hook

在这个视频中,他们所做的基本上是创建一个上下文

上下文.js

import { createContext } from "react";

export const CustomerContext = createContext(null);

Run Code Online (Sandbox Code Playgroud)

并将这些上下文传递给子组件

import Table from "./components/table";
import React, { useState } from "react";
import { CustomerContext } from "./context";
const App = () => {
  const [user, setUser] = useState(null);
  return (
    <div>
      <p> Hello World</p>
      <CustomerContext.Provider value={{ user, setUser }}>
        <Table />
      </CustomerContext.Provider>
    </div>
  );
};

export default App;
Run Code Online (Sandbox Code Playgroud)

然后在子组件中访问该值或者改变该值

import { CustomerContext } from "./../context";
import React, { useContext } from …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

5
推荐指数
1
解决办法
1885
查看次数

样式未在 React Native 中应用

我正在制作我无法在我的View组件上应用样式的自定义底部导航栏

这就是我要导入的

import React, {PureComponent} from 'react';
import {StyleSheet, View, Text} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
Run Code Online (Sandbox Code Playgroud)

然后作为渲染的回报,我这样称呼它(this.something这里是图标)

  <View styles={headerContainer1}> 
            <Text> {this.News}</Text>
            <Text>{this.home}</Text>
            <Text> {this.Exchange}</Text>
            <Text> {this.about}</Text>
            </View>
Run Code Online (Sandbox Code Playgroud)

这里我的 Header 容器看起来/来自这里

const styles = StyleSheet.create({
    headerContainer1 : {
      display: "flex",
      flexDirection: "row",
      alignItems: 'center',
      backgroundColor: "red",
      borderBottomLeftRadius: 0,
      borderBottomRightRadius: 0
    }
  })

  const { 
    headerContainer1
  } = styles;
Run Code Online (Sandbox Code Playgroud)

在这里,我做了两件事。flexDirection: "row",backgroundColor: "red"可惜我看不到任何的变化被应用。

[问题:]我错过了什么或做错了什么?我附上下面的图片以供参考

在此处输入图片说明

reactjs react-native

4
推荐指数
1
解决办法
5133
查看次数

玩笑模拟尺寸没有改变

我是第一次进行测试,所以我非常确定我做错了什么。

我正在编写测试用例,我的组件在内部执行此操作。

const {width, height} = Dimensions.get('window')
Run Code Online (Sandbox Code Playgroud)

对于我的测试用例,我考虑的是 iPhone 11,其尺寸为width: 414, height:896,并且我希望所有测试用例的尺寸保持一致。

在测试时响应本机测试库,将宽度设置为750,高度设置为1334

我想更改为iPhone 11尺寸,我在网上搜索了一些用于jest.mock更改功能的文章。

所以我做了这样的事情

it('renders correctly', () => {
     jest.mock("Dimensions", () => ({
        get: jest.fn().mockReturnValue({ width: 414, height:896 }),
     }))
      
     const {getByTestId} = render(<Home />)
 
Run Code Online (Sandbox Code Playgroud)

Home组件有console.log(width, height),但它仍然给出宽度为 750,高度为 1334(因此我的测试用例失败)。

我该如何修复它?

testing typescript jestjs react-native react-native-testing-library

4
推荐指数
1
解决办法
4361
查看次数