Cookie 挂钩在功能组件中不起作用

问题描述 投票:0回答:1

我有这个代码:

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. 你可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试和解决此问题的提示,请参阅 https://reactjs.org/link/invalid-hook-call。**

我在功能组件中使用钩子。为什么会出现这个错误?

使用 Cookie 帮助:

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 模板。 CookiesHelp 中的 useState 不要抛出异常。

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

我可能需要在 App.js 中使用 useCookies 吗?

javascript reactjs cookies
1个回答
0
投票

我遇到了同样的问题,即使在功能组件中调用 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
© www.soinside.com 2019 - 2024. All rights reserved.