I setup this reducer.js file to use React's useReducer
https://reactjs.org/docs/hooks-reference.html#usereducer
import {useReducer} from 'react';
const initialState = {
test: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case 'reset':
return initialState;
case 'addTest':
return {test: state.test + 1};
case 'removeTest':
return {test: state.test - 1};
}
};
export const getReducer = () => {
return useReducer(reducer, initialState);
};
Run Code Online (Sandbox Code Playgroud)
Now I can get state and dispatch via getReducer in different rendering functions:
import React from 'react';
import …Run Code Online (Sandbox Code Playgroud) 由于我正在学习如何使用钩子构建 React 表单,因此我浏览了 3 篇以这篇文章告终的快报。一切都很顺利,直到我进入最后一步,当您使用以下命令创建自定义挂钩时:
function useFormInput(initialValue) {
const [value, setValue] = useState(initialValue);
function handleChange(e) {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
};
}
Run Code Online (Sandbox Code Playgroud)
输入是:
const Input = ({ type, name, onChange, value, ...rest }) => (
<input
name={name}
type={type}
value={value}
onChange={event => {
event.preventDefault();
onChange(name, event.target.value);
}}
{...rest}
/>
);
Run Code Online (Sandbox Code Playgroud)
表格是:
const Form = () => {
const email = useFormInput("");
const password = useFormInput("");
return (
<form
onSubmit={e =>
e.preventDefault() || alert(email.value) || alert(password.value)
} …Run Code Online (Sandbox Code Playgroud) 我正在用 React 钩子重写一个 CRUD 表。下面的自定义钩子useDataApi用于获取表的数据,观察 url 更改 - 因此它会在 params 更改时触发。但我还需要在删除和编辑后获取最新的数据。我怎样才能做到这一点?
const useDataApi = (initialUrl, initialData) => {
const [url, setUrl] = useState(initialUrl)
const [state, dispatch] = useReducer(dataFetchReducer, { data: initialData, loading: true })
useEffect(() => {
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' })
const result = await instance.get(url)
dispatch({ type: 'FETCH_SUCCESS', payload: result.data })
}
fetchData()
}, [url])
const doFetch = url => {
setUrl(url)
}
return { ...state, doFetch }
}
Run Code Online (Sandbox Code Playgroud)
由于 …
我正在尝试在我的组件中测试功能,基本思想是设置了一些状态,当按下按钮时,将调用具有设置状态的函数。代码有效,但是当我尝试测试它时,我没有得到预期的结果,就好像在测试期间从未设置过状态一样。
我在使用 Jest 和 Enzyme 测试的 React Native 应用程序中使用带有钩子 (useState) 的功能组件。
复制我的问题的一个例子是:
import React, { useState } from "react";
import { View, Button } from "react-native";
import { shallow } from "enzyme";
const Example = function({ button2Press }) {
const [name, setName] = useState("");
return (
<View>
<Button title="Button 1" onPress={() => setName("Hello")} />
<Button title="Button 2" onPress={() => button2Press(name)} />
</View>
);
};
describe("Example", () => {
it("updates the state", () => {
const button2Press = jest.fn();
const wrapper …Run Code Online (Sandbox Code Playgroud) 今天我和一位同事争论关于使用returna 中的“”键useEffect来停止代码执行。我了解到return只能在清理时使用。
问题:
useEffect(() => {
if (stateCondition) {
//do fancy stuff
return;
}
// more code to execute if condition is not met
}, [props]);
Run Code Online (Sandbox Code Playgroud)
我的看法是,我们也许应该有另一个useEffect仅在状态为 false 时才执行的方法,而不是使用return上面的“”。
我试图找到一些文件来支持我的主张,但到目前为止我还没有找到。
我在寻找什么:
我在这儿吗?是否有文件支持我的主张或其他方式?
我正在尝试在应用程序目录中编写一个 Next.js 13 时事通讯页面,该页面使用依赖于 useEffect 作为 props 的服务器端组件。useEffect 从 REST API 获取数据以获取将呈现页面内容的新闻通讯。我正在使用的代码如下。当我需要“使用客户端”进行交互时,我无法弄清楚如何配置服务器端组件以使其工作。如何确保服务器端组件在发送到客户端之前已渲染?
代码:
import Navbar from '@/components/navbar'
import Footer from '@/components/footer'
import Pagination from './pagination'
import IssueCards from './issueCards';
import { useState, useEffect } from 'react';
import axios from 'axios';
const Newsletters = () => {
const [issues, setIssues] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [issuesPerPage, setIssuesPerPage] = useState(5);
useEffect(() => {
const fetchIssue = async () => {
const res = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API}/newsletters`)
setIssues(res.data)
}
fetchIssue()
}, …Run Code Online (Sandbox Code Playgroud) reactjs server-side-rendering next.js react-props react-hooks
我最近开始了一个项目,我使用 redux/toolkit 及其查询 API 来管理我的数据。
我尝试使用自动生成的钩子,但我从打字稿中收到错误,说他们找不到它们。这是我编写的代码示例:
export const elementsApi = api.injectEndpoints({
endpoints: (build) => ({
getElements: build.query<
{
rootParentId: string;
} & GetElementReturnType,
number
>({
query: (search) => ({ url: `Menu/GetFiles${search}` }),
transformResponse: ({ data }: { data: BackendMenuType }) => {
return {
rootParentId: data.MenuId,
...getElements(data),
};
},
providesTags: (result, _error, id) => [{ type: elements, id }],
}),
}),
});
export const { useGetElementsQuery } = elementsApi;
Run Code Online (Sandbox Code Playgroud)
当我尝试获取钩子时收到的错误消息:
Property 'useGetElementsQuery' does not exist on type 'Api<BaseQueryFn<string …Run Code Online (Sandbox Code Playgroud) 这是一个非常简单的客户端组件:
'use client';
import {useEffect, useState} from "react";
export default function MultiplePosts({posts, session, slug}) {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count has been updated:', count);
}, []);
function incrementCount() {
setCount(count + 1);
}
return (
<div className={"post-infinite-container"}>
<p>Count: {count}</p>
<button onClick={() => incrementCount()}>Increment</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
从一开始我想将它用作无限滚动,但面临问题。当我以某种方式与 useState 交互时 - 它冻结了选项卡,我什至无法关闭它。即使在这个非常简单的例子中我也面临着它。
我已经阅读了大量有关我的问题的其他问题,但找不到解决方案。这已经让我抓狂了。
我已经做了什么:
拜托,也许有人在我之前遇到过这个问题。我只是不明白为什么会发生这种情况。导致这个问题的原因太简单了。
我刚刚遇到这个问题,无法准确找到有关我的案例的任何资源。我正在构建一个使用 Spotify API 的 React 应用程序,并想要执行一个函数,该函数用“ArtistInformation”数组(一个来自 API 端点的 js 对象)填充本地 useState 对象。
此代码示例循环遍历艺术家 id 数组,并且应该仅执行 Api 函数“spotiApi.getArtistInfo(id)”一次。
当这样运行时:
const getArtistInformation = () => {
console.log("sp ids",spotifyArtistIds)
Promise.all(spotifyArtistIds.map(id => {
return spotiApi.getArtistInfo(id)
})).then(respList => {
// setArtistInfo(respList)
console.log("artistInfo", artistInfo)})
}
Run Code Online (Sandbox Code Playgroud)
代码片段运行良好并停止执行
但是当调用“setArtistInfo”useState时,循环继续无限执行
const getArtistInformation = () => {
console.log("sp ids",spotifyArtistIds)
Promise.all(spotifyArtistIds.map(id => {
return spotiApi.getArtistInfo(id)
})).then(respList => {
setArtistInfo(respList)
console.log("artistInfo", artistInfo)})
}
Run Code Online (Sandbox Code Playgroud)
这是整个组件供参考:
import { Box } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useSelector } …Run Code Online (Sandbox Code Playgroud) 我需要做什么才能等到doSomethingWithItems()完成后fetchItems()?
const [items, setItems] = useState();
const fetchItems = async () => {
try {
let responseData = await sendRequest(`${process.env.REACT_APP_BACKEND_URL}/items/user/${userId}`);
setItems(responseData.items);
} catch (err) {}
};
const doSomethingWithItems = () => {
const filteredItems = items.filter(x => x.title === 'something');
setItems(filteredItems);
}
useEffect(() => {
fetchItems(); // ** WAIT FOR THIS TO FINISH BEFORE MOVING ON **
doSomethingWithItems();
}, []);
Run Code Online (Sandbox Code Playgroud) react-hooks ×10
reactjs ×9
javascript ×4
next.js ×2
async-await ×1
enzyme ×1
forms ×1
jestjs ×1
next.js13 ×1
react-native ×1
react-props ×1
react-redux ×1
rtk-query ×1
typescript ×1