我有一个计数器和一个console.log()来useEffect记录我状态中的每个变化,但是useEffect在挂载时被调用两次。我正在使用 React 18。这是我项目的CodeSandbox和以下代码:
import { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(5);
useEffect(() => {
console.log("rendered", count);
}, [count]);
return (
<div>
<h1> Counter </h1>
<div> {count} </div>
<button onClick={() => setCount(count + 1)}> click to increase </button>
</div>
);
};
export default Counter;
Run Code Online (Sandbox Code Playgroud) 我在https://facebook.github.io/react/docs/component-specs.html上查看了Facebook的文档,它提到了如何在客户端/服务器上调用componentWillMount,而componentDidMount仅在客户端上调用.componentWillMount对服务器做了什么?
我是 reactJS 的新手,正在编写代码,以便在从 DB 加载数据之前,它会显示加载消息,然后在加载后,使用加载的数据渲染组件。为此,我同时使用了 useState 钩子和 useEffect 钩子。这是代码:
问题是,当我检查 console.log 时,useEffect 被触发了两次。因此,代码两次查询相同的数据,这是应该避免的。
下面是我写的代码:
import React from 'react';
import './App.css';
import {useState,useEffect} from 'react';
import Postspreview from '../components/Postspreview'
const indexarray=[]; //The array to which the fetched data will be pushed
function Home() {
const [isLoading,setLoad]=useState(true);
useEffect(()=>{
/*
Query logic to query from DB and push to indexarray
*/
setLoad(false); // To indicate that the loading is complete
})
},[]);
if (isLoading===true){
console.log("Loading");
return <div>This is loading...</div>
}
else {
console.log("Loaded!"); …Run Code Online (Sandbox Code Playgroud) 我正在使用JavaScript和Union平台我将如何诊断这个问题?非常感谢.
React 中有没有一种方法——无论是通过代码还是通过 React 开发工具——来查看组件是否正在ReactStrictMode中渲染?在我的梦想世界中,我可以有某种常数console.log,比如布尔值React.isStrictModeOnForThisComponentRendering;或者,当您在 React 开发工具中检查某个组件时,它会在侧面板的某个位置显示它是否在 StrictMode 下渲染。
明确地说,这个问题是:
<React.StrictMode>,尽管它也可以通过某些框架中的配置来设置,例如Next.js)StrictMode,而不是 JavaScript 的( 'use strict';) 或TypeScript 的严格模式。这是一个重载的短语,但是 watcha 会怎样呢?第一次发帖提问:)
我有一个React应用程序:
// index.js
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root'),
);
Run Code Online (Sandbox Code Playgroud)
我有 24 个jest测试套件,到目前为止,基本上是这样的:
act(() => {
render(
<Router>
<SomeComponentIWantToTest />
</Router>
);
});
Run Code Online (Sandbox Code Playgroud)
我想到将测试包装在 中更合适StrictMode,以更接近应用程序的实际渲染方式:
act(() => {
render(
<React.StrictMode>
<Router>
<SomeComponentIWantToTest />
</Router>
</React.StrictMode>
);
});
Run Code Online (Sandbox Code Playgroud)
尝试之后,我注意到以下几点:
act. 我能够修复这些地方。欢呼!另外,快速浏览一下文档,这似乎StrictMode只是开发的事情。那么,将测试(理论上与生产中将发生的情况有关)包装起来有意义吗React.StrictMode?
我在 React 中使用 AudioContext 接口制作了一个音频可视化工具,我希望用户能够启用和禁用它。
可视化工具工作正常,我也可以禁用它(我只是删除了 vis 组件)
但是,当我想再次启用它时,它告诉我:“InvalidStateError:无法在“AudioContext”上执行“createMediaElementSource”:HTMLMediaElement 之前已连接到不同的 MediaElementSourceNode。”
我想我不能在一个音频元素上同时有 2 个 ElementSource。但我无法解决这个错误。
我尝试在 useEffect 挂钩中返回audiocontext.close() ,以便我可以创建一个新的MediaElementSource(不确定它是否以这种方式工作),但它不会改变任何内容。
也许音频元素上有一个属性可以告诉我是否已经存在 MediaElementSource ?(我什么也没找到)
或者,AudioContext 接口对我来说有点太难了,因为我只是 React 的初学者,而且我只是复制粘贴现有的可视化工具......
谢谢您的帮助!
这是我的可视化组件中的一些代码:
useEffect(() => {
var context = new AudioContext(); //Some visualiser stuff
var src = context.createMediaElementSource(audio);// The error is here
src.crossOrigin = "anonymous";
var analyser = context.createAnalyser();
src.connect(analyser);
analyser.connect(context.destination);
analyser.fftSize = 1024;
// Some canvas stuff here
//
return () => {
context.close() // doesn't work ?
};
}, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 EditorJS 的编辑器。一切工作正常,除了当我第一次加载页面时,它会在开始时初始化两个编辑器,并在每次重新加载页面时不断附加新编辑器。但它们都在<div id='editorjs' />div内部。我有什么遗漏的吗?
// react etc. imports
import EditorJS from '@editorjs/editorjs'
const EditorComponent = (props) => {
const [input, setInput] = useState({})
const currentuser = useSelector((state) => state.currentuser)
const editor = new EditorJS({
holderId: 'editorjs',
autofocus: true,
})
const postNews = () => {
// POSTING SUTFF
}
return (
<Grid>
<Grid templateRows='auto min-content' gap={6}>
<div id='editorjs' />
<Button onClick={postNews}>Post news</Button>
</Grid>
</Grid>
)
}
Run Code Online (Sandbox Code Playgroud)
这是 dom 的屏幕截图,其中加载页面后立即添加了两个编辑器。
我正在重构我们的一些组件,所以我正在尝试合并 memoization,因为某些组件可能会使用相同的值重新呈现(例如,热链接的图像 URL,除非它们相同)。
我有一个简单的组件:
const CardHeader = props => {
// img is a stringand showAvatar is a boolean but it's always true
const { ..., showAvatar, img } = props;
return (
<CardHeader>
<ListItem>
// AvatarImage shouldn't re-render if img is the same as previous
{showAvatar && <AvatarImage img={img} />
</ListItem>
</CardHeader>
);
}
Run Code Online (Sandbox Code Playgroud)
然后是AvatarImage:
const AvatarImage = React.memo(props => {
console.log("why is this still re-rendering when the img value hasn't changed?");
const { img …Run Code Online (Sandbox Code Playgroud) 我有一个组件,我设置了一个计数,并在单击按钮时让状态更新。但是当我检查渲染时间时,每次单击按钮时它都会渲染两次。
https://codesandbox.io/s/brave-forest-yre6y?file=/src/App.js
export default function App() {
const cute = Array(10).fill({});
const [count, setCount] = useState(2);
console.log(count);
return (
<div className="App">
<button
onClick={() => {
if (count < 10) setCount(count + 1);
}}
>
add
</button>
{cute.map((data, index) => {
if (index < count) {
return (
<div>
<p>{index}. Luna is cute</p>
</div>
);
}
})}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我想知道:
我有以下问题。我有一个组件需要在安装时调用 API。我在 useCallback 中进行调用,如下所示:
const sendCode = useCallback(() => {
console.log('InsideSendCode');
}, []);
Run Code Online (Sandbox Code Playgroud)
然后我在 useEffect 中调用这个函数,如下所示:
useEffect(() => {
sendCode();
}, [sendCode]);
Run Code Online (Sandbox Code Playgroud)
问题是,即使使用 useCallback,该消息也会在控制台中显示两次,我发现这将是唯一的选择。
我知道 StrictMode,但我不想禁用它。
如果每个人都能发表意见,那就太好了。
谢谢。
在我的React / Redux / ReactRouterV4应用程序的一小部分中,我具有以下组件层次结构,
- Exhibit (Parent)
-- ExhibitOne
-- ExhibitTwo
-- ExhibitThree
Run Code Online (Sandbox Code Playgroud)
在展览的孩子中,也可以绘制大约6种不同的可能路线。不用担心,我将用一些代码进行解释。
这是我的家长展览组件:
export class Exhibit extends Component {
render() {
const { match, backgroundImage } = this.props
return (
<div className="exhibit">
<Header />
<SecondaryHeader />
<div className="journey"
style={{
color: 'white',
backgroundImage: `url(${backgroundImage})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center-center'
}}>
<Switch>
<Route path={`${match.url}/exhibit-one`} component={ExhibitOne} />
<Route path={`${match.url}/exhibit-two`} component={ExhibitTwo} />
<Route path={`${match.url}/exhibit-three`} component={ExhibitThree} />
<Redirect to="/" />
</Switch>
</div>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,它所做的全部工作就是显示一个展览子组件,并设置背景图像。
这是ExhibitOne子组件之一:
export default …Run Code Online (Sandbox Code Playgroud) reactjs ×11
javascript ×6
react-hooks ×2
audio ×1
audiocontext ×1
editorjs ×1
jestjs ×1
memo ×1
next.js ×1
optimization ×1
react-router ×1
redux ×1
unit-testing ×1
use-effect ×1
usecallback ×1
visualizer ×1
websocket ×1