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

标签 javascript reactjs authentication react-router

我正在使用 React 开发一个电子商务项目。一旦我选择了产品并希望在购物车中查看它们,我只需登录即可查看购物车中的产品。如果购物车已满,一切都很好,但如果我尝试使用空购物车登录,则会出现以下错误: “类型错误:无法读取 null 的属性‘映射’” 涉及的组件有:

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

最佳答案

如果没有产品,则需要返回一个空数组:

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

应该变成:

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

关于javascript - 为什么当我使用空购物车登录时,会出现 .map 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937135/

相关文章:

javascript - 不明白为什么不触发 onclick 事件

javascript - React : Given an array, 有效地以相反的顺序渲染元素

angularjs - 如何在 $http.get().then() AngularJS 中使用 Authentication 对象

javascript - 使用 Javascript 更改 CSS 元素

javascript - 获取给定键 json javascript 的值集列表

javascript - 从 Http (ng2) 升级到 HttpClient (ng6) 后登录请求的未定义响应

javascript - ReactJS ReactCSSTransitionGroup 仅在初始加载时设置动画

php - 如何在 PHP/MySQL 中禁用用户帐户

android - 签名 APK 中的 Linkedin 登录错误(Android)

javascript - 错误 : Type '{}' is missing the following properties from type