标签: react-hooks

如何使用React useEffect仅调用一次加载函数

useEffect阵营钩将运行在功能上传递的每一个变化.这可以进行优化,只有在所需的属性发生变化时才能调用它.

如果我想调用初始化函数componentDidMount而不是在更改时再调用它会怎么样?假设我想加载一个实体,但加载函数不需要组件中的任何数据.我们怎么能用useEffect钩子做这个?

class MyComponent extends React.PureComponent {
    componentDidMount() {
        loadDataOnlyOnce();
    }
    render() { ... }
}
Run Code Online (Sandbox Code Playgroud)

使用钩子,这可能是这样的:

function MyComponent() {
    useEffect(() => {
        loadDataOnlyOnce(); // this will fire on every change :(
    }, [...???]);
    return (...);
}
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

133
推荐指数
9
解决办法
6万
查看次数

无效的钩子调用。Hooks 只能在函数组件内部调用

我是 React 的新手,现在我想在表中显示一些记录,现在我收到了这个错误。请帮帮我。

无效的钩子调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一而发生的: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本有关如何调试和解决此问题的提示,请参阅相同的应用程序。

import React,{Component} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles(theme => ({
    root: {
      width: '100%',
      marginTop: theme.spacing(3),
      overflowX: 'auto',
    },
    table: {
      minWidth: 650,
    },
  }));

class allowance extends Component{
    constructor(){
        super();
        this.state={ …
Run Code Online (Sandbox Code Playgroud)

reactjs material-ui react-hooks

130
推荐指数
12
解决办法
29万
查看次数

第 0 行:解析错误:无法读取未定义的属性“map”

目前在我的客户端启动服务器,上面的错误是我得到的。我正在使用 Typescript、React、ESlint。我似乎无法前进,因为这个错误一直困扰着我。Eslint 的 github 页面也没有太大帮助。

在我创建 useMutation 组件并将其导出到 index.ts 后,这个错误出现了,不知道如何摆脱这个错误。

Below is my package.json
Run Code Online (Sandbox Code Playgroud)
    {
    "name": "tinyhouse_client",
    "version": "0.1.0",
    "private": true,
      "dependencies": {
      "@testing-library/jest-dom": "^4.2.4",
      "@testing-library/react": "^9.3.2",
      "@testing-library/user-event": "^7.1.2",
      "@types/jest": "^24.0.0",
      "@types/node": "^12.0.0",
      "@types/react": "^16.9.35",
      "@types/react-dom": "^16.9.0",
      "@typescript-eslint/parser": "^3.0.2",
      "react": "^16.13.1",
      "react-dom": "^16.13.1",
      "react-scripts": "3.4.1",
      "typescript": "~2.23.0"
      },
      "resolutions": {
     "@typescript-eslint/eslint-plugin": "^2.23.0",
     "@typescript-eslint/parser": "^2.23.0",
     "@typescript-eslint/typescript-estree": "^2.23.0"
     },
     "scripts": {
     "start": "react-scripts start",
     " build": "react-scripts build",
     "test": "react-scripts test",
     "eject": "react-scripts eject"
     },
     "eslintConfig": {
     "extends": "react-app"
     },
     "browserslist": { …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs eslint react-hooks

110
推荐指数
9
解决办法
4万
查看次数

无法解决来自 @material-ui/core@4.12.4 的依赖错误对等 React@"^16.8.0 || ^17.0.0"

在尝试安装时npm install,出现以下错误,如何解决?

$

npm install
        npm ERR! code ERESOLVE
        npm ERR! ERESOLVE unable to resolve dependency tree
        npm ERR!
        npm ERR! While resolving: sssclub@0.1.0
        npm ERR! Found: react@18.1.0
        npm ERR! node_modules/react
        npm ERR!   react@"^18.0.0" from the root project
        npm ERR!
        npm ERR! Could not resolve dependency:
        npm ERR! peer react@"^16.8.0 || ^17.0.0" from @material-ui/core@4.12.4
        npm ERR! node_modules/@material-ui/core
        npm ERR!   @material-ui/core@"^4.12.4" from the root project
        npm ERR!
        npm ERR! Fix the upstream dependency conflict, or retry
        npm ERR! this …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

78
推荐指数
4
解决办法
14万
查看次数

如何在React Hooks useEffect上比较oldValues和newValues?

假设我有3个输入:rate,sendAmount和receiveAmount.我把3个输入放在useEffect diffing params上.规则是:

  • 如果sendAmount发生了变化,我会计算出来 receiveAmount = sendAmount * rate
  • 如果receiveAmount发生了变化,我会计算出来 sendAmount = receiveAmount / rate
  • 如果费率改变,我计算receiveAmount = sendAmount * rate何时sendAmount > 0或我计算sendAmount = receiveAmount / rate何时receiveAmount > 0

这是代码框https://codesandbox.io/s/pkl6vn7x6j来演示这个问题.

有没有办法比较oldValuesnewValues喜欢,componentDidUpdate而不是为这种情况下制作3个处理程序?

谢谢


这是我的最终解决方案usePrevious https://codesandbox.io/s/30n01w2r06

在这种情况下,我不能使用多个useEffect因为每个更改导致相同的网络调用.这也是我也用它changeCount来跟踪变化的原因.这changeCount也有助于跟踪仅来自本地的更改,因此我可以防止因服务器更改而进行不必要的网络调用.

reactjs react-hooks

77
推荐指数
8
解决办法
4万
查看次数

useNavigate() 只能在 <Router> 组件的上下文中使用

请参阅下面的我的代码。我正在尝试添加此按钮,使用它返回上一页,react-router-dom但出现以下错误,并且网站上的所有组件都消失了。

错误:

useNavigate() 只能在组件上下文中使用

我的代码:

function App() {
  const navigate = useNavigate();
  return (
    <BrowserRouter>
      <div>
      <button onClick={() => navigate(-1)}>go back</button>
        <Nav/>
        <Routes>
          <Route exact path="/" element={<Home/>}/>
          <Route exact path="/home" element={<Home/>}/>
          <Route exact path="/upcoming/:user" element={<Upcoming/>}/>
          <Route exact path="/record/:user" element={<Record/>}/>
          <Route path="*" element={<NotFound/>}/>
        </Routes>
      </div>
    </BrowserRouter>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是我在控制台中收到的错误:

错误

reactjs jestjs react-router react-router-dom react-hooks

76
推荐指数
4
解决办法
19万
查看次数

了解 React Hooks 'exhaustive-deps' lint 规则

我很难理解 'exhaustive-deps' lint 规则。

我已经阅读了这篇文章这篇文章,但我找不到答案。

这是一个带有 lint 问题的简单 React 组件:

const MyCustomComponent = ({onChange}) => {
    const [value, setValue] = useState('');

    useEffect(() => {
        onChange(value);
    }, [value]);

    return (
        <input 
           value={value} 
           type='text' 
           onChange={(event) => setValue(event.target.value)}>
        </input>
    )
} 
Run Code Online (Sandbox Code Playgroud)

它需要我添加onChangeuseEffect依赖项数组。但在我的理解中onChange永远不会改变,所以它不应该存在。

通常我是这样管理的:

const MyCustomComponent = ({onChange}) => {
    const [value, setValue] = useState('');

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

    return (
        <input 
           value={value} 
           type='text'
           onChange={handleChange}>
        </input> ?
    )
} …
Run Code Online (Sandbox Code Playgroud)

reactjs eslint react-hooks

75
推荐指数
2
解决办法
6万
查看次数

如何在React Hooks中使用componentWillMount()?

在React的官方文档中提到 -

如果您熟悉React类生命周期方法,则可以将useEffect Hook视为componentDidMount,componentDidUpdate和componentWillUnmount的组合.

我的问题是 - 我们如何componentWillMount()在钩子中使用lifecyle方法?

javascript jsx reactjs react-hooks

69
推荐指数
9
解决办法
5万
查看次数

React useEffect 导致:无法对未安装的组件执行 React 状态更新

获取数据时,我得到:无法对未安装的组件执行 React 状态更新。该应用程序仍然有效,但反应表明我可能导致内存泄漏。

这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。”

为什么我不断收到此警告?

我尝试研究这些解决方案:

https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal

https://developer.mozilla.org/en-US/docs/Web/API/AbortController

但这仍然给了我警告。

const  ArtistProfile = props => {
  const [artistData, setArtistData] = useState(null)
  const token = props.spotifyAPI.user_token

  const fetchData = () => {
    const id = window.location.pathname.split("/").pop()
    console.log(id)
    props.spotifyAPI.getArtistProfile(id, ["album"], "US", 10)
    .then(data => {setArtistData(data)})
  }
  useEffect(() => {
    fetchData()
    return () => { props.spotifyAPI.cancelRequest() }
  }, [])
  
  return (
    <ArtistProfileContainer>
      <AlbumContainer>
        {artistData ? artistData.artistAlbums.items.map(album => {
          return (
            <AlbumTag
              image={album.images[0].url}
              name={album.name}
              artists={album.artists}
              key={album.id}
            />
          )
        })
        : null}
      </AlbumContainer>
    </ArtistProfileContainer> …
Run Code Online (Sandbox Code Playgroud)

javascript fetch reactjs react-hooks

67
推荐指数
6
解决办法
16万
查看次数

在 useEffect 中,不提供依赖数组和提供空数组有什么区别?

我认为useEffectHook 在每次渲染后运行,如果提供了一个空的依赖数组:

useEffect(() => {
  performSideEffect();
}, []);
Run Code Online (Sandbox Code Playgroud)

但是这和下面的有什么区别呢?

useEffect(() => {
  performSideEffect();
});
Run Code Online (Sandbox Code Playgroud)

注意[]结尾的缺失。linter 插件不会发出警告。

reactjs react-hooks use-effect

65
推荐指数
3
解决办法
2万
查看次数