简体   繁体   English

为什么当我用空的购物车登录时,.map出现错误?

[英]Why when I login with the empty shopping cart it gives me an error with .map?

I'm working on an e-commerce project with React. 我正在与React一起进行电子商务项目。 Once I have chosen the products and want to see them in the cart,I just have to login to see the products inside the cart. 一旦选择了产品并希望在购物车中看到它们,我只需登录即可查看购物车中的产品。 Everything is fine if the cart is full, but if I try to login with the empty cart it gives me the following error: "TypeError: Cannot read property 'map' of null" The components involved are: 如果购物车已满,一切都很好,但是如果我尝试使用空购物车登录,则会出现以下错误:“ TypeError:无法读取null的属性'map'。”涉及的组件包括:

//SignInForm.js
export default class SignInForm extends React.Component{
constructor(props){
    super(props);
    this.state={
        username: '',
        password: '',
        error: null
    }
    this.handleChange= this.handleChange.bind(this);
    this.handleSubmit= this.handleSubmit.bind(this);
  }
  handleChange(e){
    let target = e.target;
    let value = target.type === 'checkbox' ? target.checked : target.value;
    let name = target.name;
    this.setState({
      [name]: value,
      error: null
    });
  }
  handleSubmit(e){
    e.preventDefault();
    console.log('The form was submitted with the following data:');
    console.log(this.state);
    const user = {
      email: this.state.username,
      password: this.state.password
    }
    axios.post(`https://reqres.in/api/login`, user)
    .then(res => {
      console.log(res);
      console.log(res.data);
      localStorage.setItem('user', res.data.token);  
        this.props.history.push('/Shopping')
      })    
  };
  render(){
    return(
      <div>              
        <form onSubmit={this.handleSubmit}>                
           <span>Username</span>                    
              <FormGroup controlId="username" bsSize="large">            
                <FormControl
                   type='text'
                   name="username"
                   placeholder='Email'
                   value={this.state.email}
                   onChange={this.handleChange}                        
                 />
               </FormGroup>                 
            <span>Password</span>                    
              <FormGroup controlId="password">            
                 <FormControl
                   type='password'
                   value={this.state.password}
                   onChange={this.handleChange}
                   name="password"
                   placeholder='Password'                                           
                 />
              </FormGroup>                  
           <Button type="submit">
            Login
            </Button>
                {
                  this.state.error !== null ? 
                  <div>
                    {this.state.error}
                  </div>
                  : ''
                }
              </form>
         </div>
    )
  }
}
withRouter(SignInForm);
NavLink(SignInForm);

//Shopping.js, the error is reported in this file
class Shopping extends Component{ 
    componentDidMount(){
        const products =  JSON.parse(localStorage.getItem('products'));
        this.setState({products});    
    }
    render(){
        const products =  JSON.parse(localStorage.getItem('products'));        
        return(
            <div >                 
                {products.map((product, key) =>
                  <CartProduct key={key} data={product}/> 
                 )}                                            
            </div>
        )
    }
}
export default Shopping;

//CartProduct.js
class CartProduct extends React.Component{   
    render(){   
        return(
        ( localStorage.getItem('products') !== null) ? (                   
            <> 
            <Row>
                <Col>
                    <img 
                        src={this.props.data.img}                       
                    />
                </Col>
                <Col>
                    <h4>{this.props.data.name}</h4>
                    <span>{this.props.data.description}</span>
                    <h4>${this.props.data.price}</h4>
                </Col>
                <Col>
            </>
            ):(
                <span>Your cart is empty!</span>
            )
        )
    }
}
export default withRouter(CartProduct);  

You need to return an empty array if there are no products: 如果没有产品,则需要返回一个空数组:

const products =  JSON.parse(localStorage.getItem('products '));

should become: 应该变成:

 const products =  JSON.parse(localStorage.getItem('products')) || [];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试更改购物车数量时控制台返回错误 - Console returns error when I try to change the quantity of shopping cart 隐藏购物车(如果为空) - Hide shopping cart if is empty 未登录和登录后如何处理购物车系统? - How to handle shopping cart system when not login and after login? 购物车/登录状态-没有Cookie? - Shopping Cart/Login State - No Cookies? fetch 给了我一个完整的数组,但是当我尝试访问它时它是空的 - fetch gives me a full array but it is empty when i try to access it 当商品从购物车中移除时,如何显示“空购物车”字样? - How to show the words "empty cart" when an item is removed from the shopping cart? 我正在使用 jQuery 在传单地图中插入地标。 但是当我尝试通过单击链接插入地标时,它给了我错误 - I'm inserting placemarks in leaflet map with jQuery. But when I try to insert the placemarks by clicking a link it gives me error 为什么我的 JavaScript appendchild 在创建列表时给我一个错误 - why my JavaScript appendchild gives me an error when it to create list 这是我添加到购物车的代码,当我单击添加到购物车时,它给了我额外的空行,这是我不想要的 - this is my add to cart code when i click on add to cart it is giving me extra empty row which i don't want 当我运行此代码时出现 MongoDB 错误,它给了我该错误 - MongoDB error when i run this code it gives me that error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM