我在反应中遇到Cookie的导出错误

时间:2018-10-29 09:24:55

标签: reactjs cookies

我确实有此代码,并且我将第一次使用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 个答案:

答案 0 :(得分:1)

错误很明显,react-cookie没有默认导出,因此您不能像导入

   import Cookie from 'react-cookie';

您需要按如下所示导入它

  import { Cookies } from 'react-cookie';

这也不是Cookie,而是Cookie。您导入错误

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

答案 1 :(得分:0)

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

仔细阅读package readme

// 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);