我目前正在将我的应用程序更新为React 16.8,因此可以使用很棒的新钩子功能。更新React包(以及所有依赖项)不是问题,一切正常。但是,当我尝试设置ESLint时,当我尝试使用钩子时,它总是给我以下错误:
在函数“ projectInfo”中调用React Hook“ useEffect”,该函数既不是React函数组件也不是自定义的React Hook函数
我的组件看起来像这样:
import React, { useState} from 'react';
const myComponent = () => {
const [counter, setCounter] = useState(0);
return <span onClick={() => setCounter(counter + 1)}>{counter}</span>;
};
export default myComponent;
Run Code Online (Sandbox Code Playgroud)
我的.eslintsrc文件如下所示:
{
"extends": ["react-app"],
"plugins": [
"react-hooks"
],
"rules": {
"no-console": ["warn", { "allow": ["info", "error"] }],
"quotes": ["warn", "single"],
"semi": ["warn", "always"],
"no-debugger": ["warn"],
"eqeqeq": ["warn"],
"no-else-return": ["warn"],
"no-extra-bind": ["warn"],
"jsx-a11y/href-no-hash": false,
"prefer-destructuring": [
"warn",
{
"array": true,
"object": true
}, …Run Code Online (Sandbox Code Playgroud) 我想使用useRef挂钩来更改DOM元素的样式:
const Box = props => {
const box = useRef(0);
const onClick = () => {
box.current.backgroundColor = "blue";
};
return (
<div>
<div
ref={box}
style={{ width: "300px", height: "300px", backgroundColor: "red" }}
/>
<button onClick={onClick}>Change color of box</button>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
但是,如果单击按钮的backgroundColor,box则不会更改。
我还创建了一个简单的代码段,它说明了我的问题。
我正在使用钩子,但出现此错误
第25行:在函数“ contact”中调用React Hook“ React.useState”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks第26行:React Hook“ React.useState”是在既不是React函数组件也不是自定义React Hook函数的函数“ contact”中调用react-hooks / rules-of-hooks第27行:在都不是React的函数“ contact”中调用React Hook“ React.useState”功能组件或自定义的React Hook函数react-hooks / rules-of-hooks
export default function contact() {
const [messageInput, setMessageInput] = React.useState("");
const [email, setEmail] = React.useState("");
const [name, setName] = React.useState("");
const enables =
messageInput.length > 0 &&
email.length > 0 &&
name.length > 0;
return (
<div className="App">
Run Code Online (Sandbox Code Playgroud)
我之前也做过类似的项目,现在以旧项目为参考。这在我的旧项目中没有发生。
<select>在React中使用受控的HTML 标签时。
关于以下代码段:
工作原理:
选项1
function changeSelect(event) {
const newValue = event.target.value;
setNestedState((prevState) => {
return({
...prevState,
propA: newValue
});
});
}
Run Code Online (Sandbox Code Playgroud)
这不是吗?(仅在第一次更改时有效)
选项#2
function changeSelect(event) {
setNestedState((prevState) => {
return({
...prevState,
propA: event.target.value
});
});
}
Run Code Online (Sandbox Code Playgroud)
SNIPPET(使用选项2)
function changeSelect(event) {
const newValue = event.target.value;
setNestedState((prevState) => {
return({
...prevState,
propA: newValue
});
});
}
Run Code Online (Sandbox Code Playgroud)
function changeSelect(event) {
setNestedState((prevState) => {
return({
...prevState,
propA: event.target.value
});
});
}
Run Code Online (Sandbox Code Playgroud)
我正在使用几个星期前发布的React Router的新useHistory挂钩。我的React-router版本是5.1.2。我的React版本为16.10.1。您可以在底部找到我的代码。
但是,当我从react-router导入新的useHistory时,出现此错误:
Uncaught TypeError: Cannot read property 'history' of undefined
这是由React-router中的这一行引起的
function useHistory() {
if (process.env.NODE_ENV !== "production") {
!(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React >= 16.8 in order to use useHistory()") : invariant(false) : void 0;
}
return useContext(context).history; <---------------- ERROR IS ON THIS LINE !!!!!!!!!!!!!!!!!
}
Run Code Online (Sandbox Code Playgroud)
由于它与useContext有关,并且可能与上下文冲突有问题,因此我尝试完全删除对useContext的所有调用,创建提供程序等。但是,此操作无济于事。试过React v16.8; 一样。我不知道是什么原因造成的,因为React路由器的所有其他功能都可以正常工作。
***请注意,调用其他React路由器挂钩(例如useLocation或useParams)时,也会发生相同的情况。
有人遇到过这种情况么?有什么想法可能导致这种情况吗?任何帮助将不胜感激,因为我在网上没有找到与此问题相关的信息。
import React, {useEffect, useContext} from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { …Run Code Online (Sandbox Code Playgroud) reactjs react-router react-router-dom react-context react-hooks
useEffect 即使依赖项数组具有常量对象,也会被触发。
我尝试提取逻辑并将对象放入 useState
const payload = {
limit: 5,
offset: 0,
filterBy: 'All',
};
useEffect(() => {
const defaultPayload = {
limit: 10,
offset: 0,
filterBy: 'All',
};
dispatch({ type: RANDOM_CONST, payload: payload || defaultPayload });
}, [dispatch, payload]);
Run Code Online (Sandbox Code Playgroud)
它应该仅在payload更改时触发。由于payload是一个常数,因此它应该只运行一次并记下无限次。
我试图让调光器仅在点击ETH或Select a token按钮点击时显示。我什至无法让状态部分工作,所以我可以连接按钮。
function Main () {
const [accountAddress, setAccountAddress] = useState(null);
const [show, setShow] = useState(false);
return (
<div ref={contextRef}>
<Dimmer.Dimmable as={Segment} dimmed={show}>
<Grid style={styles.grid}>
<Grid.Row>
<Grid.Column>
<Card style={styles.card} centered>
<Card.Content>
<Card.Header style={styles.padding}>Swap / Pool</Card.Header>
<Input style={styles.padding} fluid type='text' placeholder='0.0'>
<Label basic>From</Label>
<input />
<Button>ETH <Icon name='angle down' /></Button>
</Input>
<Input style={styles.padding} fluid type='text' placeholder='0.0'>
<Label basic>To</Label>
<input />
<Button>Select a Token <Icon name='angle down' /></Button>
</Input>
<Button style={styles.padding} color='teal' fluid size='large'>
Connect Wallet
</Button> …Run Code Online (Sandbox Code Playgroud) 我正在开发一个使用 React 查询、https ://react-query.tanstack.com/、React 钩子和功能组件的 React JS 项目。但是当我对 API 调用使用反应查询时它会抛出错误。
这是我的组件以及我如何在其中使用查询。
const App = () => {
const [ list, updateList ] = useState([])
const info = useQuery(["item-list"], getList, {
retry: false,
refetchOnWindowFocus: false,
})
if (info.status == "success") {
updateList(info.data)
}
return (
//view components here
)
}
Run Code Online (Sandbox Code Playgroud)
这是我的 getList API 调用逻辑
export const getList= async () => {
const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
return data;
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的代码时,我收到以下错误:
react-dom.development.js:14815 未捕获的错误:重新渲染太多。React 限制渲染次数以防止无限循环。
我的代码有什么问题?
我正在学习 React 并遇到以下棘手的问题,在下面的代码输出如下
输入 3
这里 0
根据我的理解,setVideos已经为Videos数组设置了值,那么为什么返回的长度为 0 ?
const [Videos, setVideos] = useState([])
useEffect(() => {
axios.get('/api/video/getVideos')
.then(response => {
if (response.data.success) {
console.log("IN " + response.data.videos.length)
setVideos(response.data.videos)
console.log("HERE " + Videos.length);
} else {
console.log("OUT");
alert('Failed to get Videos')
}
})
}, [])
Run Code Online (Sandbox Code Playgroud) 这有效:https : //codesandbox.io/s/stoic-beaver-ucydi
使用 React Hook Form 重构后,这不起作用:https ://codesandbox.io/s/objective-cloud-bkunr?file=/src/ControlledTextField.tsx
我最近使用Fluent UI构建了一个有状态的 React 表单,并将字段包装在自定义组件中。
我已经包含了一个功能,当您在站点标题字段中键入时,会生成站点 URL 字段中的值(在我的情况下,它只是复制字段值并删除对 URL 无效的字符)。
(简化的)代码运行良好,如下所示:
import * as React from 'react';
import {useState} from 'react';
import { PrimaryButton } from 'office-ui-fabric-react';
import SiteTitleField from '../../../common/formFields/SiteTitleField';
import SiteUrlField from '../../../common/formFields/SiteUrlField';
export default function MyForm(props) {
const urlPrefix: string = "https://" + window.location.hostname + "/sites/";
const [siteTitle, setSiteTitle] = useState();
const [titleErrorMessage, setTitleErrorMessage] = useState('');
const [siteUrl, …Run Code Online (Sandbox Code Playgroud) react-hooks ×10
reactjs ×10
javascript ×4
eslint ×1
html ×1
react-query ×1
react-router ×1
yup ×1