cookie钩在功能组件中不起作用

发布于 2025-01-23 14:29:33 字数 3462 浏览 2 评论 0原文

我有此代码:

import React from 'react'
import { useCookies } from 'react-cookie'

const CookiesHelp = () => {
    const [cookies, setCookie] = useCookies(['token'])

    const setToTrue = () => {
        setCookie('token', 'true')
    }

    return (
        <>
            <label>{cookies.token}</label>
            <button onClick={setToTrue}>Set true</button>
        </>
    )
}

export default CookiesHelp

当我运行应用程序时,我有一个错误:

** react.development.js:209警告:无效的挂钩呼叫。钩子只能在功能组件的主体内部调用。这可能是出于以下原因之一:

  1. 您可能有不匹配的react版本和渲染器(例如react dom),
  2. 会打破挂钩规则
  3. 您可能 请参阅 https://reactjs.org/link/link/link/invalid-hook-call 关于如何调试和解决此问题。**

我在功能组件中使用钩子。为什么发生此错误?

使用CookiesHelp:

export default class App extends Component {
    static displayName = App.name;

    constructor(props) {
        super(props);
        this.state = { forecasts: [], loading: true }
    }

    componentDidMount() {
        this.populateWeatherData()
    }

    static renderForecastsTable(forecasts) {
        return (
            <table className='table table-striped' aria-labelledby="tabelLabel">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Temp. (C)</th>
                        <th>Temp. (F)</th>
                        <th>Summary</th>
                    </tr>
                </thead>
                <tbody>
                    {forecasts.map(forecast =>
                        <tr key={forecast.date}>
                            <td>{forecast.date}</td>
                            <td>{forecast.temperatureC}</td>
                            <td>{forecast.temperatureF}</td>
                            <td>{forecast.summary}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
    }

    render() {
        let contents = this.state.loading
            ? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p>
            : App.renderForecastsTable(this.state.forecasts);

        return (
            <>
                <div>
                    <h1 id="tabelLabel">Weather forecast</h1>
                    <p>This component demonstrates fetching data from the server.</p>
                    {contents}
                </div>
                <UploadPicture />
                <CookiesHelp />
            </>
        );
    }

    async populateWeatherData() {
        const response = await fetch('https://localhost:7054/WeatherForecast');
        const data = await response.json();
        this.setState({ forecasts: data, loading: false });
    }
}

默认的Visual Studio ReactJS + WebAPI模板。 usestate 在cookieshelp中不要抛出例外。

root.render(
    <CookiesProvider>
        <App />
    </CookiesProvider>
);

我可能需要在app.js中使用 usecookies 吗?

I have this code:

import React from 'react'
import { useCookies } from 'react-cookie'

const CookiesHelp = () => {
    const [cookies, setCookie] = useCookies(['token'])

    const setToTrue = () => {
        setCookie('token', 'true')
    }

    return (
        <>
            <label>{cookies.token}</label>
            <button onClick={setToTrue}>Set true</button>
        </>
    )
}

export default CookiesHelp

And when I run my app, I have an error:

**react.development.js:209 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.**

I use hook in functional component. Why this error has occured?

Using CookiesHelp:

export default class App extends Component {
    static displayName = App.name;

    constructor(props) {
        super(props);
        this.state = { forecasts: [], loading: true }
    }

    componentDidMount() {
        this.populateWeatherData()
    }

    static renderForecastsTable(forecasts) {
        return (
            <table className='table table-striped' aria-labelledby="tabelLabel">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Temp. (C)</th>
                        <th>Temp. (F)</th>
                        <th>Summary</th>
                    </tr>
                </thead>
                <tbody>
                    {forecasts.map(forecast =>
                        <tr key={forecast.date}>
                            <td>{forecast.date}</td>
                            <td>{forecast.temperatureC}</td>
                            <td>{forecast.temperatureF}</td>
                            <td>{forecast.summary}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
    }

    render() {
        let contents = this.state.loading
            ? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p>
            : App.renderForecastsTable(this.state.forecasts);

        return (
            <>
                <div>
                    <h1 id="tabelLabel">Weather forecast</h1>
                    <p>This component demonstrates fetching data from the server.</p>
                    {contents}
                </div>
                <UploadPicture />
                <CookiesHelp />
            </>
        );
    }

    async populateWeatherData() {
        const response = await fetch('https://localhost:7054/WeatherForecast');
        const data = await response.json();
        this.setState({ forecasts: data, loading: false });
    }
}

Default Visual Studio ReactJS + WebAPI template. useState in CookiesHelp don't throw an exception.

root.render(
    <CookiesProvider>
        <App />
    </CookiesProvider>
);

May be I need use useCookies in App.js?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記憶穿過時間隧道 2025-01-30 14:29:33

我遇到了同样的问题,即使在功能组件中被调用时,SetCookie也无法正常工作。
我通过将React-Cookie重新安装在正确的位置来解决,事实证明,我的React-App已将Node_Modules安装在两个不同的级别上,并导致React模块在React-Cookie代码中未定义。

app
 |node_modules     <-- where packages should be
 |package.json
node_modules
package.json       <-- deleted those and reinstalled in app

I had the same issue, setCookie wasn't working even when being called in functional component.
I solved this by reinstalling react-cookie in the correct place, turns out my react-app had node_modules installed in two different levels and was causing React module to be undefined inside react-cookie code.

app
 |node_modules     <-- where packages should be
 |package.json
node_modules
package.json       <-- deleted those and reinstalled in app
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文