小编Rob*_*ell的帖子

正确使用UseCallBack

目前,每次更新查询参数时,我的代码都会重新呈现。一旦我删除查询参数;但是,我收到一条警告,指出“React Hook useCallback 缺少依赖项:'query'。要么包含它,要么删除依赖项数组react-hooks/exhaustive-deps”。我尝试在 useEffect 中定义 getData 函数,但我在 useEffect 之外将 getData 用作 onclick 函数。我想要完成的是最初在反应挂钩上获取文章,然后仅在提交时获取新数据,而不是在更新查询时获取新数据,并且也不会收到有关查询缺少依赖项的任何警告。任何建议都会有很大帮助。代码如下:

import React, { useState, useEffect, useCallback } from "react"
import axios from "axios"

const Home = () => {
  const [data, setData] = useState(null)
  const [query, setQuery] = useState("react hooks")

  const getData = useCallback(async () => {
    const response = await axios.get(
      `http://hn.algolia.com/api/v1/search?query=${query}`
    )
    setData(response.data)
  }, [query])

  useEffect(() => {
    getData()
  }, [getData])

  const handleChange = event => {
    event.preventDefault()
    setQuery(event.target.value)
  }

  return (
    <div>
      <input …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

7
推荐指数
1
解决办法
2万
查看次数

使用状态更新 Formik 初始值之一会重置所有其他值

我目前正在使用 formik 构建一个表单。我能够按预期更新每个字段(姓名、电子邮件、电话)。我遇到的问题是当我为 formik 初始值之一提供状态值并更新该状态时。更新状态的行为会导致表单完全重置输入字段有没有办法在不重置整个表单的情况下更新测试状态?我的代码如下:

import { useState } from "react";
import { Formik, FieldArray } from "formik";
import "./styles.css";

export default function App() {
  const [test, setTest] = useState(null);
  return (
    <Formik
      enableReinitialize
      initialValues={{
        test: test,
        name: "",
        email: "",
        phone: ""
      }}
    >
      {({
        values,
        touched,
        errors,
        handleChange,
        handleBlur,
        handleSubmit
      }) => (
        <>
          <button onClick={() => setTest("something")}>Update State</button>
          <br />
          <input
            placeholder="name"
            type="text"
            name="name"
            value={values.name}
            onChange={handleChange}
          />
          <br />
          <input
            placeholder="email"
            type="text"
            name="email"
            value={values.email}
            onChange={handleChange}
          />
          <br …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs formik

6
推荐指数
1
解决办法
1万
查看次数

登录时从用户集合中获取用户数据

我目前正在开发一个在客户端初始化了 firebase 的应用程序。当用户通过 firebase 登录时,我想从 firestore 获取用户的数据。我目前正在onAuthStateChanged侦听器中执行此操作并成功获取用户。我想知道这是否是获取用户数据的最佳方式。我的代码如下:

  const [currentUser, setCurrentUser] = useState(null)
  const [authState, setAuthState] = useState(false)

  useEffect(() => {
    console.log('state unknown')
    setAuthState(false)
    auth().onAuthStateChanged(user => {
      if (!user) {
        return
      }
      const sourceRef = firestore()
        .collection('users')
        .where('userId', '==', user.uid)
      sourceRef
        .get()
        .then(snapshot => {
          if (snapshot.empty) {
            console.log('user not found')
          } else {
            let data = {}
            snapshot.forEach(item => (data = item.data()))
            console.log(data)
            setCurrentUser(data)
            setAuthState(true)
          }
        })
        .catch(error => console.log(error.code))
    })
  }, [])

  return (
    <AppContext.Provider value={{ currentUser, …
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs firebase-authentication google-cloud-firestore

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

使用 React router dom 滚动到新页面上的特定 div

我目前正在使用 React router dom 在我的 React 应用程序中进行路由。我正在尝试使用 React router dom 中的链接滚动到另一个页面上的特定 div。我遇到的问题是页面发生变化但它没有滚动到我指定的 div 的 id。我不确定我错过了什么。

我的代码如下:App.js

import { Switch, Route, BrowserRouter as Router } from "react-router-dom";

import Home from "./Home";
import PageTwo from "./PageTwo";
import "./styles.css";
function App() {
  return (
    <Router>
      <div className="App">
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/pagetwo" component={PageTwo} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

Home Page
Run Code Online (Sandbox Code Playgroud)
import { Link } from "react-router-dom";

const Home = () => {
  return (
    <div>
      <div>Navigate …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-router-dom

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

是的,基于嵌套对象内的嵌套对象进行验证

我目前有一个如下所示的对象:

const initialValues = {
  created: {
    position: 1,
    name: 'created',
    type: 'timestamp',
    desc: 'The date and time the lead is created',
    mapping: {
      name: '',
      defaultValue: '',
      map: false
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望当映射对象中的映射值设置为 true 时,映射对象中的名称成为必需的。我已尝试通过执行以下操作:

const validationSchema = yup.object({
  created: yup.object().when('mapping.map', {
    is: true,
    then: yup.object({
      mapping: yup.object({
        name: yup.string().required('name is required')
      })
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

我相信我没有足够的隧道来准确设置映射对象的验证,任何和所有帮助/建议将不胜感激。

javascript reactjs yup formik

2
推荐指数
1
解决办法
4778
查看次数

上传到 Firebase 时调整图像大小或压缩图像

以下谷歌云功能可以正确上传图像,但我还想压缩图像,以避免因上传大文件而产生不必要的费用。任何建议将不胜感激!!!代码如下:

exports.uploadImage = (req, res) => {
  const BusBoy = require("busboy")
  const path = require("path")
  const os = require("os")
  const fs = require("fs")


  const busboy = new BusBoy({ headers: req.headers })

  let imageToBeUploaded = {}
  let imageFileName

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== `image/jpeg` && mimetype !== `image/png`) {
      return res.status(400).json({ error: `Not an acceptable file type` })
    }

    // my.image.png => ['my', 'image', 'png']
    const imageExtension = filename.split(".")[filename.split(".").length - 1]
    // 32756238461724837.png
    imageFileName = …
Run Code Online (Sandbox Code Playgroud)

javascript node.js google-cloud-storage firebase busboy

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

没有未使用的变量

在我的 useState 钩子中,我正在导入上下文;因此, setUser 将不再使用并给我和 Eslinting 警告。我不确定如何扼杀这个警告,并且为此没有任何想法。如果有人在 React 中提出建议或最佳实践来抑制此警告,我将不胜感激。代码如下:

import React, { useContext } from 'react'
import { Link } from 'react-router-dom'
// Material UI
import Button from '@material-ui/core/Button'
import Grid from '@material-ui/core/Grid'
import Container from '@material-ui/core/Container'
import User from './User'
// context
import { ProfileContext } from '../contexts/ProfileContext'
const Header = ({ isAuth, logout }) => {
  const [user, setUser] = useContext(ProfileContext)
  return (
    <Container maxWidth="lg" style={{ padding: 10 }}>
      <Grid container justify="space-between">
        <Grid item xs={2}>
          <Button color="inherit" component={Link} …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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