标签: react-hooks

在React Hooks中使用push方法(useState)?

如何推送元素里面的useState数组React hook?这是反应状态下的旧方法吗?还是新的东西?

例如setState推送示例

javascript reactjs react-hooks

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

使用React Hooks重置为初始状态

我目前正在使用注册表单,以下是我的代码段:

const Signup = () => {
    const [username, setUsername] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [passwordConfirmation, setPasswordConfirmation] = useState('')

    const clearState = () => {
        setUsername('')
        setEmail('')
        setPassword('')
        setPasswordConfirmation('')
    }

    const handleSubmit = signupUser => e => {
        e.preventDefault()
        signupUser().then(data => {
            console.log(data)
            clearState() // <-----------
        })
    }

    return <JSX />
}

export default Signup
Run Code Online (Sandbox Code Playgroud)

每个状态都用于表格的受控输入。

本质上,我想做的是在用户成功注册后,希望状态恢复为初始状态,并清除字段。

手动将每个状态设置回空字符串是非常必要的,clearState因为我想知道React是否附带有方法或函数来将状态重置为初始值?

reactjs react-hooks

25
推荐指数
4
解决办法
2万
查看次数

ESLint:组件定义缺少 displayName (react/display-name)

我正在使用带有 antd 的 react hook 组件。为表设置列时,渲染函数给我一个 ESLint 错误:

ESLint:组件定义缺少 displayName (react/display-name)

我试过将 displayName 添加到对象中,但这不起作用。

这是错误的样子: 在此处输入图片说明

这是代码:

const columns_payment_summary_table = [ 
    {
      title: FooConstants.LABEL_QUANTITY_SELECTED,
      dataIndex: 'group',
      key: 'group',
      render: text => (
        <span>{getCountForCountry(text)}</span>
      ),
    }
  ]
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗?

这是完整的组件代码(只是相关位)

import * as FooConstants from './constants'
import {connect} from 'react-redux'
import React, {useState, useEffect} from 'react'
import {Card, Table} from 'antd'
import PropTypes from 'prop-types'

const propTypes = {
  foos: PropTypes.object.isRequired,
}

function Foos(props) {

  const [selectedFooRows, setSelectedFooRows] = useState([])

  useEffect(() => { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs antd react-hooks

25
推荐指数
4
解决办法
4万
查看次数

为什么需要具有功能更新表单的 React useState?

我正在阅读有关功能更新的React Hook 文档并查看此引用:

“+”和“-”按钮使用函数形式,因为更新的值是基于之前的值

但是我看不出需要功能更新的目的是什么,它们与直接使用旧状态计算新状态有什么区别。

为什么 React useState Hook 的更新器函数根本需要函数式更新表单? 我们可以清楚地看到差异的示例有哪些(因此使用直接更新会导致错误)?

例如,如果我从文档中更改此示例

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

count直接更新:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

25
推荐指数
4
解决办法
7536
查看次数

Why React Hook useState uses const and not let

The standard way to use a React useState Hook is the following:

const [count, setCount] = useState(0);
Run Code Online (Sandbox Code Playgroud)

However this const count variable is clearly going to be reassigned to a different primitive value.

Why then is the variable not defined as let count?

javascript ecmascript-6 reactjs react-hooks

25
推荐指数
2
解决办法
1095
查看次数

使用参数反应 useCallback

使用 React 的useCallbackhook 本质上只是一个useMemo专门用于函数的包装器,以避免在组件的 props 中不断创建新的函数实例。我的问题来自何时需要将争论传递给从备忘录创建的回调。

例如,像这样创建的回调......

const Button: React.FunctionComponent = props => {
    const onClick = React.useCallback(() => alert('Clicked!'), [])
    return <button onClick={onClick}>{props.children}</button>
}
Run Code Online (Sandbox Code Playgroud)

是一个记忆化回调的简单示例,不需要将外部值传递给它来完成其工作。但是,如果我想为React.Dipatch<React.SetStateAction>函数类型创建一个通用的记忆回调,那么它需要参数......例如:

const Button: React.FunctionComponent = props => {
    const [loading, setLoading] = React.useState(false)
    const genericSetLoadingCb = React.useCallback((x: boolean) => () => setLoading(x), [])

    return <button onClick={genericSetLoadingCb(!loading)}>{props.children}</button>
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这似乎与执行以下操作完全相同......

const Button: React.FunctionComponent = props => {
    const [loading, setLoading] = React.useState(false)
    return <button onClick={() => setLoading(!loading)}>{props.children}</button>
}
Run Code Online (Sandbox Code Playgroud)

这会让记忆函数的目的落空,因为它仍然会在每次渲染时创建一个新函数,因为它也会在每次渲染时genericSetLoadingCb(false)返回一个新函数。 …

callback reactjs react-hooks

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

在函数内部使用 RTK-Query 挂钩的方法?

我已经使用 Axios 成功编写了我的应用程序来获取内容。截至目前,它已设置为在发生某些事件时获取内容(例如单击提交按钮)。但是,我正在尝试Redux 的 RTK 查询解决方案。该包生成挂钩,并在其示例中提供了在挂载时调用挂钩的简单组件级示例。

我如何利用这些 rtk-hook(以及一般的钩子),以便将它们与 、 和条件事件等行为联系onClick起来onSubmit我知道这与hooks 规则准则相冲突,但我无法想象 RTK-Query 会受到如此限制,只允许组件级 onMount API 调用。

当我试图解决这个问题/等待一个有用的例子时,我正在阅读一些相关文章:

第二篇文章似乎有些相关,但我觉得它偏离了道路太远,并且正在质疑它是否值得rtk-query安装。我不妨只使用它axios,因为它可以在我的组件和逻辑中的任何地方使用。有人可以教育我如何解决这个问题吗?我是 rtk-query 的新手,它看起来真的很酷,但它的实现方法似乎也确实受到限制。

这是我的切片的示例api.ts

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const apiEndpoint = 'http://localhost:5000';

export const myApi = createApi({
  reducerPath: 'myApi',
  baseQuery: fetchBaseQuery({ baseUrl: apiEndpoint }),
  endpoints: builder => ({
    getFileById: builder.query<any, { id: string; fileId: string }>({
      query: arg => { …
Run Code Online (Sandbox Code Playgroud)

reactjs redux react-hooks redux-toolkit rtk-query

25
推荐指数
2
解决办法
3万
查看次数

使用react-hooks在更新状态时执行异步代码

我有类似的东西:

const [loading, setLoading] = useState(false);

...

setLoading(true);
doSomething(); // <--- when here, loading is still false. 
Run Code Online (Sandbox Code Playgroud)

设置状态仍然是异步的,那么等待此setLoading()调用完成的最佳方法是什么?

setLoading()似乎并没有接受一个回调像setState()使用.

一个例子

基于类的

getNextPage = () => {
    // This will scroll back to the top, and also trigger the prefetch for the next page on the way up.
    goToTop();

    if (this.state.pagesSeen.includes(this.state.page + 1)) {
      return this.setState({
        page: this.state.page + 1,
      });
    }

    if (this.state.prefetchedOrders) {
      const allOrders = this.state.orders.concat(this.state.prefetchedOrders);
      return this.setState({
        orders: allOrders,
        page: this.state.page …
Run Code Online (Sandbox Code Playgroud)

javascript callback reactjs react-hooks

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

如何在React Hook中使用油门或反跳?

我正在尝试throttle在功能组件中使用lodash中的方法,例如:

const App = () => {
  const [value, setValue] = useState(0)
  useEffect(throttle(() => console.log(value), 1000), [value])
  return (
    <button onClick={() => setValue(value + 1)}>{value}</button>
  )
}
Run Code Online (Sandbox Code Playgroud)

由于内部方法useEffect在每次渲染时都会重新声明,因此限制效果不起作用。

有没有人有一个简单的解决方案?

throttling lodash reactjs react-hooks

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

Updating and merging state object using React useState() hook

I'm finding these two pieces of the React Hooks docs a little confusing. Which one is the best practice for updating a state object using the state hook?

Imagine a want to make the following state update:

INITIAL_STATE = {
  propA: true,
  propB: true
}

stateAfter = {
  propA: true,
  propB: false   // Changing this property
}
Run Code Online (Sandbox Code Playgroud)

OPTION 1

From the Using the React Hook article, we get that this is possible:

const [count, setCount] = useState(0);
setCount(count + 1); …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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