开发者问题收集

我在 React 中使用 Cookie 时遇到此导出错误

2018-10-29
4591

我确实有此代码,并且我将首次使用 Cookies,但是我收到以下错误,有谁可以帮助我修复该问题?

“我遇到的错误:尝试导入错误:'react-cookie' 不包含默认导出(导入为'Cookie')。”

import React from 'react';    
import ReactDom from 'react-dom';    
import './App.css';    
import CountDown from './CountDown';
import Basket from './Basket';    


import Cookie from 'react-cookie'
class Products extends React.Component{    

constructor(props){
    super(props);
   this.state={
       order : []  
   } 
 this.shop = this.shop.bind(this);
}  
   prevstate = [];
   `enter code here`shop(evt){

this.prevstate.push(evt.target.id);
this.setState({
    order : this.prevstate
})
console.log(Cookie.get('selected'))
Cookie.set('selected' , this.props.cart , {path :' /'});

   }

render(){
    return(
        <div className="prowrap">

         {this.props.prolist.map((name) => (
         <div  className="pro" key={name.id} style={{border:"1px red 
solid"}} >
         <img src={name.image}/>
         <p>{name.name}</p>
         <p>{name.detail}</p>  
         <p className="countdown"><CountDown time={name.date}/></p>
         <div className="price">{name.price} Euro</div>
         <button className="shop" id={name.id} onClick={this.shop}>Add To 
Cart</button>    
         </div>))}
        <Basket cart={this.state.order} allpro={this.props.prolist}/>
        </div>
    )
}
}

export default Products;
2个回答

错误很明显,react-cookie 没有默认导出,因此您无法像这样导入它

   import Cookie from 'react-cookie';

您需要像下面这样导入它

  import { Cookies } from 'react-cookie';

另外,它不是 Cookie 而是 Cookies。您错误地导入了它

当它是默认导出时,您不要使用 {} 来导入,但如果它不是默认导出,则使用 {} 来导入它。

Hemadri Dasari
2018-10-29

您需要导入类似 import { withCookies, Cookies } from 'react-cookie'; 然后导入 cookies.get('selected') ,参考下面的代码

仔细阅读 包自述文件

// App.jsx
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';

import NameForm from './NameForm';

class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  constructor(props) {
    super(props);

    const { cookies } = props;
    this.state = {
      name: cookies.get('name') || 'Ben'
    };
  }

  handleNameChange(name) {
    const { cookies } = this.props;

    cookies.set('name', name, { path: '/' });
    this.setState({ name });
  }

  render() {
    const { name } = this.state;

    return (
      <div>
        <NameForm name={name} onChange={this.handleNameChange.bind(this)} />
        {this.state.name && <h1>Hello {this.state.name}!</h1>}
      </div>
    );
  }
}

export default withCookies(App);
Shivam
2018-10-29