标签: react-hooks

如何从多个组件更新反应上下文?

所以我想了解一下,React contexts但我有点困惑。从它的文档:

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。

所以这意味着我可以将应用程序的整个状态设为全局,并且可以从任何子组件更新它,对吧?但是我对如何使用它感到困惑。我有一个小应用程序,可以根据用户的输入向用户显示登录、注册或登录屏幕。我期望以下任何组件都应该能够更改存储在上下文中的全局对象的值,但我不确定如何使用它(提到不确定的函数todos

// context
const MyAppSettings = React.createContext(
    {
        userId:null,
        enableMarketing:false,
        theme:"light"
    }
)
Run Code Online (Sandbox Code Playgroud)
//ui components(having access to local state as well as global context

function SettingsUI({onThemeChange,onConsentChange}){
    let settings = useContext(MyAppSettings)

    return(
        <div>
            <button onClick={e=>onThemeChange()}>Change Theme to {settings.theme==="light"?"dark":"light"}</button>
            <br/>
            <button onClick={e=>onConsentChange()}> {settings.enableMarketing?"withdraw consent for marketing emails":"give consent for marketing emails"}</button>
        </div>
    )


}
function Auth({onAuthClick}){
    let settings = useContext(MyAppSettings)
    let textColor = settings.theme==="light" ? "black" : "white"
    let bg = settings.theme==="light"?"white": "brown" …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-context react-hooks use-context

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

React 获取更多数据并附加到状态

当加载更多数据并附加到状态时,我遇到了经典的无限滚动问题。

我有一个页面,其中显示了自定义的无限滚动城市列表。
这些城市是从外部库中获取的。

import { City, Country, CitiesQuery } from "an-external-library";

export const CountryComponent: FC<Props> = ({ country: Country }) => {
  const [cities, setCities] = useState<City[]>([]);
  const [citiesQuery, setCitiesQuery] = useState<CitiesQuery>();

  const loadMoreCities = useCallback(() => {
    console.log("loadMoreCities", "cities", cities);

    citiesQuery
      ?.load((newCities) => {
        console.log("loadMoreCities", "newCities", newCities);
        const updatedCities = [...cities, ...newCities];
        console.log("loadMoreCities", "updatedCities", updatedCities);
        setCities(updatedCities);
      })
      .then(() => setCitiesQuery(citiesQuery))
      .catch(console.error)
  }, [cities]); // I've tried adding more dependencies here

  useEffect(() => {
    const query = country.createCitiesQuery()
    query.limit = …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs react-hooks

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

在 React 中添加和删除事件监听器是反模式吗?

考虑这个片段,

useEffect(() => {
        document.addEventListener('mousedown', checkAndCloseMenu);
        return () => document.removeEventListener('mousedown', checkAndCloseMenu);
 }, []);
Run Code Online (Sandbox Code Playgroud)

我在高阶下拉组件中使用此 useEffect,我见过很少专业人士使用此类添加和删除事件侦听器。使用这些事件监听器是反模式吗?如果是,正确的方法是什么。

javascript reactjs react-hooks

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

如何防止useSelector造成不必要的渲染?

我正在使用useSelector钩子来检索我的减速器的值,但它导致我的应用程序上出现大量不必要的渲染。

我在组件上使用哪个属性并不重要,因为它们都state从减速器获取相同的对象,每次一个属性更改时,useSelector都会渲染所有使用的组件。

这是减速机:

const initialState = {
   productsDataState: [], // => this is populated by multiple objects
   searchProducts: [],
   isSearchOn: false,
   inputValue: '',
   listOrder: [],
   toastify: ['green', ''],
   toastifyOpen: false
}

const reducer = ((state = initialState, action) => {
   switch (action.type) {
      case actionTypes.UPDATE_PRODUCT:
         return {
            ...state,
            productsDataState: action.products,
            listOrder: action.listOrder
         }
      case actionTypes.SET_TOASTIFY:
         return {
            ...state,
            toastify: action.toastify,
            toastifyOpen: action.open
         }
      case actionTypes.SET_SEARCH:
         return {
            ...state,
            searchProducts: action.searchProducts,
            isSearchOn: action.isSearchOn,
            inputValue: action.inputValue …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs redux redux-thunk react-hooks

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

更新另一个组件中钩子的属性

这是我的反应代码的简化版本。我有一个这样的钩子:

const [todo, setTodo] = useState();
Run Code Online (Sandbox Code Playgroud)

我的todo看起来像这样:

todo = {
    name: 'Name of my todo list',
    date: 2022-09-19',
    todos: [
        'groceries', 
        'do the laundry'
    ]
}
Run Code Online (Sandbox Code Playgroud)

在我的主要组件中,我将待办事项传递给“todos 组件”:

在我的 todos 组件中,我在 props 上有一个循环来显示具有 todos 值的所有输入

{todos.map(t => {
   <input 
       value={t} 
       onChange={e => {
           t = e.target.value
       }} 
   />
})
Run Code Online (Sandbox Code Playgroud)

但不幸的是它没有更新待办事项。我该怎么做呢?我无法使用 setTodo,因为我位于子组件中,setTodo 管理所有待办事项对象,而我只想更新待办事项列表。我的组件不了解完整的待办事项对象,而只了解待办事项列表。

javascript reactjs react-hooks

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

CKEditor 在每次状态/道具更改后重新渲染

目前我正在使用 Next.js 和 CKEditor 5 开发一个项目。我创建了一个要在页面上使用的编辑器组件。由于我需要父页面上输入的值,因此我使用 state 和 setState 作为道具。

我的代码如下所示:

页:

import dynamic from "next/dynamic";
import { useState } from 'react';

export default function Create() {
    const Editor = dynamic(() => import("../components/MyEditor"), { ssr: false });

    const [text, setText] = useState("")

    const handleTextInput = (textInput) => {
        setText(textInput)
    }

    return (
        <>
            <div key="editor1div">
                <Editor key="editor1" handleInput={handleTextInput} data={text} />
            </div>
        </>
    )
}
Run Code Online (Sandbox Code Playgroud)

编辑器组件:

import Editor from '../../ckeditor5-custom-build/build/ckeditor'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import '../../ckeditor5-custom-build/build/translations/de';


const MyEditor = …
Run Code Online (Sandbox Code Playgroud)

javascript ckeditor reactjs next.js react-hooks

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

&lt;input&gt; 标签上的属性 `reset` 值无效

我收到这个警告:

react-dom.development.js:86 警告:reset标签上的 prop 值无效。要么将其从元素中删除,要么传递一个字符串或数字值以将其保留在 DOM 中。详情请参见https://reactjs.org/link/attribute-behavior

这来自我的自定义挂钩:

import { useState } from 'react'

export const useField = (type) => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return {
    type,
    value,
    onChange,
    reset
  }
}
Run Code Online (Sandbox Code Playgroud)

该钩子在组件中使用:

const CreateNew = (props) => {
  const content = useField('text')
  const author = useField('text')
  const info = useField('text')

  const navigate = useNavigate()

  const handleSubmit = (e) …
Run Code Online (Sandbox Code Playgroud)

html javascript reactjs react-hooks react-custom-hooks

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

React 中的上下文值未在事件侦听器内更新

我正在用 React 构建一个简单的游戏。问题是上下文已正确更新,但事件侦听器函数内的上下文值未更新。如果我访问事件函数外部的值,则会呈现新的更新值。

对于第一个 keyup 事件,该值将为 0,但对于下一个事件,它应该是新的更新值。

  const updateGame = useUpdateGame();
  const gameData = useGameData(); 
  //Assume Default gameData.board value is 0

  // Assume context value updated to 5

  useEffect(() => {
    document.addEventListener("keyup", (e) => {
      e.stopImmediatePropagation();
      console.log(gameData.board) //0
      handleKeyPress(e.key, gameData.board, updateGame);
    });
  }, []);
  console.log(gameData.board) //5
Run Code Online (Sandbox Code Playgroud)

reactjs react-context react-hooks

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

如何像这样使用useState?这是什么意思?

谁能解释一下const rerender = React.useState(0)[1]这是什么?

import React from 'react'
import axios from 'axios'
import {
  useQuery,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"

const getCharacters = async () => {
  await new Promise((r) => setTimeout(r, 500))
  const { data } = await axios.get('https://rickandmortyapi.com/api/character/')
  return data
}

const getCharacter = async (selectedChar) => {
  await new Promise((r) => setTimeout(r, 500))
  const { data } = await axios.get(
    `https://rickandmortyapi.com/api/character/${selectedChar}`,
  )
  return data
}

const queryClient = …
Run Code Online (Sandbox Code Playgroud)

prefetch rerender reactjs react-hooks

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

如何根据 React Native 中按下的 Pressable 显示图标?

我有一个多个 Pressable 组件。我怎样才能做到当我点击摩托车可压件时,检查图标将显示在其旁边,如果在三轮可压件上,检查图标将显示在其旁边,而摩托车图标上的图标将消失。

在此输入图像描述

我尝试创建一个状态,但它同时将所有图标设置到位。这是代码:

  const [checkIcon, setCheckIcon] = useState(false)

<Pressable
            style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
              onPress={() => setCheckIcon(true)}
            >
              <Image source={require("../assets/motorcycle.png")} style={styles.modalFieldImage} />
              <View style={styles.modalFieldVehicleNameContainer}>
                <Text style={styles.modalFieldText}>Motorcycle</Text>
                <Text style={styles.modalFieldTextDescription}>Cheapest option perfect for small-sized items</Text>
                <Text style={styles.modalFieldTextDescription}>Up to 20 kg</Text>
              </View>
              {
                checkIcon === true ? <Icon name="check" type="font-awesome-5" size={hp("3%")} color="#322C6A" style={styles.modalFieldIcon} /> : null
              }
            </Pressable>

            <Pressable
              style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
              onPress={() => …
Run Code Online (Sandbox Code Playgroud)

icons state reactjs react-native react-hooks

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