我基本上正在学习 Jest,我必须为 useEffect() 钩子编写一个测试用例,该钩子基于 flag[counter] 进行渲染,并在内部检查字段是否存在 localStorage 值。
function sample(props) {
const counter = props;
const [displayIcon, setDisplayIcon] = useState(counter);
function isLocalstoragePresent() {
return localStorage.getItem("some_Id");
}
useEffect(() => {
if (isLocalstoragePresent()) {
setDisplayIcon(true);
} else {
setDisplayIcon(false);
}
}, [counter]);
export default sample;
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我编写测试用例/为内部调用 isLocalstoragePresent() 方法的 UseEffect 提供指导吗?提前致谢。
我有一个Provider通过两个提供状态变量及其相应的设置器的方法contexts。
const BookedBatchContext = createContext({})
const SetBookedBatchContext = createContext(null)
const initialState = {
id: null
}
Run Code Online (Sandbox Code Playgroud)
看起来Provider像这样:
export const BookedBatchProvider = ({ children }: { children: any }) => {
const [bookedBatch, setBookedBatch] = useState(localState ||initialState)
return (
<SetBookedBatchContext.Provider value={setBookedBatch}>
<BookedBatchContext.Provider value={bookedBatch}>
{ children }
</BookedBatchContext.Provider>
</SetBookedBatchContext.Provider>
)
}
Run Code Online (Sandbox Code Playgroud)
通过自定义挂钩,我可以将其setBookedBatch提供给其他组件:
export const useBookedBatch = () => {
const bookedBatch = useContext(BookedBatchContext)
const setBookedBatch = useContext(SetBookedBatchContext)
return { bookedBatch, setBookedBatch }
}
Run Code Online (Sandbox Code Playgroud)
当尝试使用该 …
我只是使用 create-react-app 设置制作一个简单的食谱获取应用程序,但是当我尝试记录响应时,它记录了两次。我向后退并删除了代码,直到它停止发生,并且无论出于何种原因,当我使用状态挂钩时它都会开始:
import React, { useState } from 'react';
import './App.css';
function App() {
const APP_ID = '092fa53f';
const APP_KEY = '6fcf8c591c129cc3d01aefbda0d8a4d8';
const recipe_url = `https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`;
const [recipes, setRecipes] = useState(0);
return (
<div className="App">
{console.log('test')}
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud) 我写了以下代码:
function CreateModal({toggleCreatePorjectModal, fetchProjects}) {
const [formObj, setFormObj] = useState({name: "", link: "", error: ""})
function validateLinkAndCreateProject() {
if(formObj.link.trim() === "" || formObj.name.trim() === "") {
setFormObj(state => ({...state, error: "ALL fields are mandatory, please enter Project Name and Feed Link to create project."}))
return
}
rssFeedParser(formObj.link.trim())
.then((res) => {
axios.post(`${ServerPath}/projects/create`, {
name: formObj.name,
link: formObj.link
})
.then(response => {
if(response.data.error) {
setFormObj(state => ({...state, error: "Something went wrong. Please try again after some time."}))
} else {
fetchProjects()
toggleCreatePorjectModal(false) …Run Code Online (Sandbox Code Playgroud) 我想将 4 个“hi”存储在一个数组中。代替:
strArr.push('hi');
strArr.push('hi');
strArr.push('hi');
strArr.push('hi');
Run Code Online (Sandbox Code Playgroud)
我这样做了:
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:错误:重新渲染次数过多。React限制渲染次数以防止无限循环
我不知道出了什么问题,我想知道当 i=3 时它是否没有达到。所以我做了检查:
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
if(i==3){
console.log("done")
}
}
Run Code Online (Sandbox Code Playgroud)
‘i’的值确实达到了3,但是为什么我的代码又运行了?
这是我的代码:
function MyApp(){
const [strArr, setStrArr] = useState([]);
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
if(i==3){
console.log("done")
}
}
return(
<div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud) AFAIK,在 React 函数组件中,必须使用useEffect如下componentWillUnmount功能:
useEffect(()=>{
return console.log("component unmounting");
},[])
Run Code Online (Sandbox Code Playgroud)
我正在制作一个表单页面,并希望在用户退出页面时提交进度。所以我正在考虑在清理过程中提交。
但是,如果我不将formData状态放入依赖项数组中,则状态将在清理过程中过时。
如果我确实formData将其放入依赖项数组中,则每次formData.
如何保持状态新鲜,但仅在“真正卸载”中运行清理?
const [formData, setFormData] = useState({
input1: 'input1 default',
input2: 'input2 default',
}); // track the form data
useEffect(()=>{
return () => {
axios.post(myFormSubmitURL, formData);
}
}, []); // this will submit the stale data
useEffect(()=>{
return () => {
axios.post(myFormSubmitURL, formData);
}
}, [formData]); // this will submit the data every time it changes
Run Code Online (Sandbox Code Playgroud) 我有一个像这样的领域
const SimpleReactComponent = (props) => {
const [title, setTitle] = useState('DEFAULT')
useEffect(() => {
return () => {
// unmount
console.log(`[${title}] while unmounting`)
}
}, [])
return <TextInput value={title} onChangeText={title => setTitle(title)}></TextInput>
}
Run Code Online (Sandbox Code Playgroud)
当我修改该title字段并离开该组件时,它仍然打印以下内容
[DEFAULT] while unmounting
Run Code Online (Sandbox Code Playgroud)
虽然我期待新修改的值而不是DEFAULT.
如何在组件卸载时捕获更改?
如果我有一个变量,其值可以根据另一个属性的值完全派生,那么初始化计算变量与使用useState/的组合useEffect来跟踪变量是否有任何后果/陷阱?让我用一个人为的例子来说明:
/**
* ex paymentAmounts: [100, 300, 400]
*/
const Option1 = ({paymentAmounts}) => {
const [average, setAverage] = useState(paymentAmounts.reduce((acc, curr) => curr + acc, 0) / paymentAmounts.length)
useEffect(() => {
setAverage(paymentAmounts.reduce((acc, curr) => curr + acc, 0) / paymentAmounts.length)
}, [paymentAmounts])
return (
<div>
Average: {average}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
或者更简单地说
/**
* ex paymentAmounts: [100, 300, 400]
*/
const Option2 = ({paymentAmounts}) => {
const average = paymentAmounts.reduce((acc, curr) => curr + acc, 0) / …Run Code Online (Sandbox Code Playgroud) 我正在研究 React hooks 并在代码中插入一些控制台日志,以更好地理解渲染流程。然后我开始模拟发送相同值的 setState 效果,看看 React 是否会再次渲染它。
import { useState } from "react";
function ManComponent() {
/* States */
const [shirt, setShirt] = useState("Blue Shirt");
console.log("Rendering man with "+shirt);
/* Actions */
const changeShirt = (newShirt) => {
console.log("[Man] Changing shirt from "+shirt+" to "+newShirt);
setShirt(newShirt);
};
return (
<div>
<p>The man is using: {shirt}</p>
<div>
<button onClick={() => changeShirt("Red Shirt")}>Change to red shirt</button>
<button onClick={() => changeShirt("Blue Shirt")}>Change to blue shirt</button>
</div>
</div>
);
}
export default function …Run Code Online (Sandbox Code Playgroud) 我正在使用 React 构建一个简单的时钟应用程序。目前该countDown()功能有效,但我希望用户能够通过按下按钮来停止/启动时钟。我有一个名为的状态布尔值,paused当用户单击按钮时该状态布尔值会反转。问题在于,在 的值反转后,对传递给的函数内部paused的引用似乎正在访问 的默认值,而不是更新后的值。pausedcountDown()setInterval()paused
function Clock(){
const [sec, setSecs] = useState(sessionLength * 60);
const [paused, setPaused] = useState(false);
const playPause = () => {
setPaused(paused => !paused);
};
const countDown = () => {
if(!paused){
setSecs(sec => sec - 1)
}
}
useEffect(() => {
const interval = setInterval(() => {
countDown();
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
Run Code Online (Sandbox Code Playgroud)
setState()我假设它与 React 中调用的异步性质和/或使用正则表达式时范围/上下文的性质有关。然而,我无法通过阅读与这些概念相关的文档来确定发生了什么。
我可以想到一些解决方法,让我的应用程序能够按需要运行。但是我想了解我当前的方法有什么问题。我将不胜感激任何人都可以阐明这一点!
reactjs ×10
use-state ×10
use-effect ×6
javascript ×4
react-hooks ×2
arrays ×1
console ×1
jestjs ×1
post ×1
react-native ×1
setinterval ×1
typescript ×1
unit-testing ×1