ReactJS 加载函数“不是函数”

IT技术 javascript reactjs
2021-04-02 15:30:57

我正在设置一个 react-cookie npm 包,但尝试加载 cookie 以调用用户,但得到的不是函数。我该如何正确设置?

这是我现在尝试过的。当有人输入用户 id 名字和姓氏时,它将转到http://192.168.1.163:3000/users/页面。

import React, { Component } from 'react';
import '../sass/main.scss';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import ModalLogin from '../components/Modal/Login';
import ModalSignup from '../components/Modal/Signup';
import { Cookies } from 'react-cookie';
import axios from 'axios';

class App extends Component {
    constructor() {
      super();
      // call user and that 
      var user = Cookies.load('user');
      var that= this;
      this.state = {name: null, signedIn: false}

      //  When someone put in user id first-name and last-name it will go to http://192.168.1.163:3000/users/ page
      if (user){
        axios.get('http://192.168.1.163:3000/users/' + user.id)
          .then(function (response) {
            console.log(response);
            that.setState({name: response.data.data.attributes['first-name'] + ' ' + response.data.data.attributes['last-name'], signedIn: true});
            //this.setState({ showModal: false });
          })
          .catch(function (error) {
            console.log(error);
          });
        }
      this.render.bind(this);
    }

    render() {
        return (
          <Navbar expand="lg">
              <Navbar.Brand href="#home">Kommonplaces</Navbar.Brand>
              <Navbar.Toggle aria-controls="basic-navbar-nav" />
              <Navbar.Collapse id="basic-navbar-nav">
                <Nav className="ml-auto">
                  <Nav.Link href="#activities">Activities</Nav.Link>
                  <Nav.Link href="#space">List Your Space</Nav.Link>
                  <Nav.Link className={this.state.signedIn === true ? 'hidden' : ''}>Sign up</Nav.Link>
                  <Nav.Link className={this.state.signedIn === true ? 'hidden' : ''}>Log in</Nav.Link>
                </Nav>
              </Navbar.Collapse>
          </Navbar>
        );
    }
}

export default App;```
1个回答

你可能正在寻找get方法Cookies

  var user = Cookies.get('user');

https://github.com/reactivestack/cookies/tree/master/packages/react-cookie#getname-options

嘿@Rikin,当我尝试使用 get 时,我忘了说这会带来与 load 方法相同的问题。
2021-05-23 15:30:57
这是您可能正在寻找的一个很好的用法示例,它也包装了 HOC 以访问 Cookies.get github.com/reactivestack/cookies/issues/...
2021-06-13 15:30:57
@BrandonPowell 您能否详细说明您使用时遇到的问题/错误 get
2021-06-14 15:30:57
当然,使用后出现的问题/错误get TypeError: react_cookie__WEBPACK_IMPORTED_MODULE_6__.Cookies.get is not a function.
2021-06-19 15:30:57