标签: react-hooks

带拖动手柄的 Dnd-kit 可排序列表 - setActivatorNodeRef 无效

我对dnd-kit库有疑问。我正在尝试使用拖动手柄激活器实现可排序列表。问题是我无法将拖动手柄(按钮)设置为仅拖动激活器。相反,整个父元素保持活动状态。

SortableItem成分:


    const SortableItem: FunctionComponent<{ id: string }> = (props) => {
      const {
        attributes,
        listeners,
        setNodeRef,
        setActivatorNodeRef,
        transform,
        transition,
      } = useSortable({ id: props.id });


      const context: Context = {
        attributes: attributes,
        listeners: listeners,
        setActivatorNodeRef: setActivatorNodeRef
      }


      return (
        <SortableItemContext.Provider value={context}>
          <div ref={setNodeRef} {...attributes} {...listeners}>
            {props.children}
          </div>
        </SortableItemContext.Provider>
      );
    }

Run Code Online (Sandbox Code Playgroud)

DragHandle成分:


    export const DragHandle: FunctionComponent = () => {

      const { attributes, listeners, setActivatorNodeRef } = useContext(SortableItemContext);
      return <button type="button"
                     className="DragHandle"
                     {...attributes} {...listeners}
                     ref={setActivatorNodeRef}>
        <svg viewBox="0 …
Run Code Online (Sandbox Code Playgroud)

drag-and-drop reactjs react-hooks dnd-kit

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

这个价差操作符是如何、为什么工作的

这是代码

funtion App(){
  const [Cards, setCards] = useState([
    {id: 0 , name: 'Harry Potter'},
    {id: 1 , name: 'Hermonie Granger'},
    {id: 2 , name: 'Ron Weasly'},])

  const shuffle = (arr)=>{
    // just shuffle the arr then return it.
  }
    
   return (
    <div className="App">
      
      <div>{Cards[0].name}</div>
      
      <button onClick={() => {
        setCards([...shuffle(Cards)])
        console.log(Cards)
        
        }}>Testing</button>
    </div>
  );

}
Run Code Online (Sandbox Code Playgroud)

为什么这个有效setCards([...shuffle(Cards)]) ,而不是这个setCards(shuffle(Cards))

即使我不使用展开运算符,它也会洗牌(请参阅控制台),但不会在页面中显示它。

:) ;) ....

spread reactjs react-hooks

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

React-query 中的 persistQueryClient 如何工作?

我正在使用 React Query 进行 API 调用,但是当我重新加载页面时,状态会丢失。我在 StackOverflow 上发布了一个问题,询问是否有一种方法可以在 React-Query 中保存数据,然后有人回答说有一种方法可以使用 persistQueryClient,但我尝试阅读文档,但我仍然不明白它是如何工作的。有人可以向我解释一下吗?

https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient

typescript reactjs react-hooks react-query

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

useCallback 如何帮助代码运行得更快?

所以据说useCallback可以缓存一个函数,我认为目的是让代码运行得更快。

例如,如果我有:

  const handleChange = (ev) => {
    setMsg(ev.target.value);
  };
Run Code Online (Sandbox Code Playgroud)

我也可以将其更改为:

  const handleChange = useCallback((ev) => {
    setMsg(ev.target.value);
  }, []);
Run Code Online (Sandbox Code Playgroud)

这样现在函数就被缓存了。但是,每次重新渲染组件时是否都需要创建此函数?

为了测试它,我将其更改为 IIFE,以便从其中吐出该函数,并且它会打印出该函数正在吐出。

请参阅: https ://codesandbox.io/s/jolly-nightingale-zxqp8k

因此,每次当您在输入字段中输入内容时,都会输出一个新函数,如控制台中所示。因此,这意味着 IIFE 每次都会以任何方式执行,这意味着即使它不是 IIFE,函数文字每次也会被制作成函数对象。那么这如何帮助代码运行得更快呢?

reactjs react-hooks

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

为什么在 useState 中设置 React 组件是一种不好的做法?

为什么将组件存储为状态值是不好的做法?

const [Component, setComponent] = useState<JSX.Element>(<Empty />);
Run Code Online (Sandbox Code Playgroud)

假设我想根据许多不同的标准(所有条件都是互斥的)有条件地渲染一个组件。但在实际渲染之前,我想添加一个去抖动器(在x不活动的毫秒后延迟渲染)。我不一定会这样做,但它似乎更直观,并且只需将组件分配为状态值(在这种情况下)的代码就更少。我可以设置我的状态来保存文本值,在任何地方引用该值,并设置一个映射变量以将字符串映射到组件。但这似乎没有必要。我在网上读到这是一种不好的做法,你应该只将数据放入状态,但每个人似乎都方便地忽略了为什么是一种不好的做法。文档中似乎没有任何内容表明这是不好的做法。

这是一个有效的示例,希望能够说明为什么在状态中设置组件很方便。每个Message组件都会被记住,React.memo因此它们的 props 不会改变:

import React, { useState, useEffect } from 'react';
import useDebounce from '../../hooks/useDebounce';
import {
  TooShort,
  NoPrompt,
  LimitWarning,
  LimitReached,
  Empty,
} from './Messages';

interface Props {
  promptAreaTouched: boolean;
  promptText: string;
  debounceTimeout?: number;
}

const DEBOUNCE_TIMEOUT = 2000;
const SHORT_PROMPT_LENGTH = 5;
const APPROACHING_PROMPT_LENGTH = 40;
const MAX_PROMPT_LENGTH = 50;

const PromptLengthMessage = ({
  promptAreaTouched,
  promptText,
  debounceTimeout = DEBOUNCE_TIMEOUT, …
Run Code Online (Sandbox Code Playgroud)

debouncing typescript reactjs react-hooks

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

有没有一种方法可以使用一个事件处理程序更新多个useState(反应挂钩)或一个useState(反应挂钩)的多个属性?

我正在使用2个字段登录表单。电子邮件和密码。当我使用代表两个字段的2 useState时,然后当我使用handleChange更新状态时,两个状态都将更新。这不是意图。

   const [email, setEmail] = useState()
   const [password, setPassword] = useState()

    const handleChange = e => {
        const {value} = e.target
        setEmail(value)
        setPassword(value)
    }
Run Code Online (Sandbox Code Playgroud)

我不想使用多个事件处理程序来处理每个输入字段。我试过了

    const [state , setState] = useState({
        email : "",
        password : ""
    })

    const handleChange = e => {
        const {name , value} = e.target
        setState({
            [name] : value
        })
    }
Run Code Online (Sandbox Code Playgroud)

但这会一次更新一个属性。并且其他财产价值迷失了。因此,有什么方法可以像使用状态组件那样用一个事件处理程序更新所有输入字段。

    this.state = {
      email : "",
      password : ""
    }

    const handleChange = e => {
        const {name , value} = e.target …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

0
推荐指数
3
解决办法
4226
查看次数

TypeError:cards.map不是函数

我正在尝试学习对钩子的反应,在这一点上,我完全不知道问题是什么。该列表正确呈现,但是当我按下按钮时,我的renderCardList()中出现“ TypeError:cards.map不是一个函数”。任何帮助将不胜感激。

当我在课堂上使用状态时它起作用

import React, { useState } from 'react';
import RentalCard from './RentalCard';

const RentalCardList = () => {
    const [cards, setCards] = useState([
        { name: 'Anne`s', price: 234 },
        { name: 'John`s', price: 83 },
        { name: 'Mary`s', price: 733 }
    ]);

    const renderCardList = () => {
        return cards.map(c => (
            <RentalCard key={Math.random()} name={c.name} price={c.price} />
        ));
    };

    const add = obj => {
        setCards(cards.push(obj));
        console.log(cards);
    };

    return (
        <div className="container">
            <section id="rentalListing">
                <h1 className="page-title">Our hot listings</h1> …
Run Code Online (Sandbox Code Playgroud)

dictionary reactjs react-hooks

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

Reading component state just after setting when using useState hook in react

This console.log is not working: It'll just print the previous state value as set is async.

const SomeCompo = () => {
  const [count, set] = useState(0);
  const setFun = () => {
    console.log(count);
    set(count + 1);
    console.log(count);    
  }
  return <button onClick={setFun}>count: {count}</button>
}
Run Code Online (Sandbox Code Playgroud)

I had to read the count in the render itself:

const SomeCompo = () => {
  const [count, set] = useState(0);
  console.log(count);
  const setFun = () => {
    set(count + 1);
  }
  return <button onClick={setFun}>count: …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

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

用useState和setInterval反应useEffect

使用以下代码通过组件DOM旋转对象数组。问题是状态永远不会更新,我不能锻炼为什么..?

    import React, { useState, useEffect } from 'react'

const PremiumUpgrade = (props) => {
    const [benefitsActive, setBenefitsActive] = useState(0)


// Benefits Details
const benefits = [
    {
        title: 'Did they read your message?',
        content: 'Get more Control. Find out which users have read your messages!',
        color: '#ECBC0D'
    },
    {
        title: 'See who’s checking you out',
        content: 'Find your admirers. See who is viewing your profile and when they are viewing you',
        color: '#47AF4A'
    }
]


// Rotate Benefit Details …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

0
推荐指数
2
解决办法
107
查看次数

反应钩无限循环

因此,我有一个项目组件,该组件从我的项目上下文中获取数据。我正在尝试选择该对象数组中的第一个对象,并将其传递到新状态。

项目组成

const projects = useContext(ProjectContext) // array of objects from context
const [selected, setSelected] = useState({}) // where i will pass projects[0]
const selectProj = (data) => {
    setSelected(data) // INFINITE LOOP ERROR
}

if (projects.length > 0) {
    selectProj(projects[0])
}
Run Code Online (Sandbox Code Playgroud)

所以我有点不知所措。

更新:我使用的答案

const projects = useContext(ProjectContext) // array of objects
const [selected, setSelected] = useState({})

const selectProj = (data) => {
    setSelected(data)
}

useEffect(() => {
    if (projects.length > 0) {
        selectProj(projects[0])
    }
}, [projects])
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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