GVKun编程网logo

类型错误:无法读取 React js(无法读取actors.json)

11

在本文中,我们将为您详细介绍类型错误:无法读取Reactjs的相关知识,并且为您解答关于无法读取actors.json的疑问,此外,我们还会提供一些关于Angular-错误类型错误:无法读取未定义的属

在本文中,我们将为您详细介绍类型错误:无法读取 React js的相关知识,并且为您解答关于无法读取actors.json的疑问,此外,我们还会提供一些关于Angular - 错误类型错误:无法读取未定义的属性“名称”、React/MaterialUI - 类型错误:无法读取未定义的属性“地图”、× 类型错误:无法读取 null 的属性“map”、“类型错误:无法读取未定义的属性‘过滤器’”以及类似的其他数组函数,如使用 ReactJS 和 redux 的 map的有用信息。

本文目录一览:

类型错误:无法读取 React js(无法读取actors.json)

类型错误:无法读取 React js(无法读取actors.json)

如何解决类型错误:无法读取 React js?

提交表单时出现错误,错误如下..

TypeError: 无法读取未定义的属性 ''payload''

如果你想知道更多信息告诉我

reducer/index.js

export default (posts =[],action) => {
   switch(action.type){
       case ''FETCH_ALL'':
            return action.payload;
        case ''CREATE'':
            return [...posts. action.payload];
       default:
            return posts;
   
   }

}

操作/posts.js

import * as api from ''../api'';

//动作创建者

export const getPosts = () => async (dispatch) => {
    try {
        const { data } = await api.fetchPosts();
        dispatch({ type: ''FETCH_ALL'',payload: data })
    } catch (error) {
        console.log(error.message)
    }

}

export const createPost = (post) => async (dispatch) =>{
    try{
        const {data} = await api.createPost(post);
        dispatch({type: ''CREATE'',payload:data})
    }catch(error){
        console.log(error);
    }
}

API/index.js

import axios from ''axios'';

const url = "http://localhost:7000/posts";

export const fetchPosts = () =>  axios.get(url);

export const createPost = (newPost) => axios.post(url,newPost);
  

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Angular - 错误类型错误:无法读取未定义的属性“名称”

Angular - 错误类型错误:无法读取未定义的属性“名称”

如何解决Angular - 错误类型错误:无法读取未定义的属性“名称”?

在我的 Angular-12 项目中,我使用以下代码注册用户并使用 Laravel-8 api 将图像插入到目录和数据库中:

界面:

export interface ICompanySetup {
  companyName: string;
  registrationNumber: string;
  dateEstablished: Date;
  company_logo: any;
 }

服务:

createCompanySignup(data: any): Observable<ICompanySetup[]> {
  return this.http.post<ICompanySetup[]>(this.api.baseURL + ''signup'',data,this.httpOption);
}

组件:

import {
  ApiService
} from ''src/app/services/api.service'';

export class SignupComponent implements OnInit {
  isLinear = true;
  isLoading = false;
  companySetupForm!: FormGroup;
  companyForm!: FormGroup;
  idForm!: FormGroup;
  imageSrclogo!: string | ArrayBuffer;
  files: any;

  constructor(
    private fb: FormBuilder,private api: ApiService,private route: Router,) {}

  onFileChange(event: any) {
    const reader = new FileReader();

    if (event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);

      reader.onload = () => {
        this.imageSrclogo = reader.result as string;

        this.companyInfoForm.get(''company_logo'') ? .setValue(file);
      };

    }
  }

  ngOnInit() {
    this.companyForm = this.fb.group({
      companyName: ['''',[Validators.required,Validators.minLength(3),Validators.maxLength(100)]],dateEstablished: ['''',[Validators.required]],company_logo: ['''',[
        RxwebValidators.extension({
          extensions: ["jpg","jpeg","bmp","png","gif","svg"]
        })
      ]],},{
      updateOn: "blur"
    });
    this.idForm = this.fb.group({
      registrationNumber: ['''',});
  }

  get fc() {
    return this.companyForm.controls;
  };
  get fi() {
    return this.idForm.controls;
  };

  onSubmit() {
    this.isSubmitted = true;

    const formCompanyData = this.companyForm.getRawValue();
    const formIdData = this.idForm.getRawValue();

    const formData = new FormData();
    var datestr = (new Date(formCompanyData.dateEstablished)).toUTCString();
    formData.append(''companyName'',formCompanyData.companyName);
    formData.append("company_logo",this.files,this.files.name);
    formData.append(''registrationNumber'',formCompanyData.registrationNumber);
    formData.append("dateEstablished",datestr);

    this.spinnerService.show();
    const header = {
      ''Content-Type'': ''application/json''
    };

    this.isLoading = true;
    this.companyService.createCompanySignup(formData).subscribe((res: any) => {
        this.router.navigate([''admin/category'']).then(() => this.showToasterSuccess(res.message));
      },error => this.router.navigate([''admin/category'']).then(() => this.showToasterError(error[0].message))
    );;
  }
}

HTML:

<mat-horizontal-stepper [linear]="isLinear" #stepper labelPosition="bottom">
  <mat-step [stepControl]="companyForm">
    <form [formGroup]="companyForm">
      <ng-template matStepLabel matStepperIcon="phone">Company Info</ng-template>

      <div>
        <div>
          <divhttps://www.jb51.cc/tag/Box/" target="_blank">Box-profile">
            <div>
              <img[src]="imageSrclogo || ''assets/img/no-image.png''" alt="No Company logo">
            </div>

            <h3>Company logo</h3>

            <div>
              <label for="file"></label>
              <input formControlName="company_logo" id="file" type="file"(change)="onFileChange($event)">
            </div>
          </div>
        </div>
      </div>
      <div>
        <div>
          <label for="dateEstablished">Date Registered:<span>*</span></label>
          <mat-form-field fxFlex="100%" fxFlex.gt-sm>
            <input matInput [matDatepicker]="dateEstablished" placeholder="Choose a date" [max]="tomorrow" formControlName="dateEstablished" readonly required>
            <mat-datepicker-toggle matSuffix [for]="dateEstablished"></mat-datepicker-toggle>
            <mat-datepicker #dateEstablished></mat-datepicker>
          </mat-form-field>
        </div>
        <div *ngIf="fc.dateEstablished.touched && fc.dateEstablished.invalid">
          <div *ngIf="fc.dateEstablished.hasError(''required'')">
            <div>
              Date Registered is required!
            </div>
          </div>
        </div>
      </div>
      <div>
        <div>
          <label for="name">Company Name:<span>*</span></label>}
          <input type="text" formControlName="companyName" placeholder="Company Name"required/>
        </div>
        <div *ngIf="fc.companyName.touched && fc.companyName.invalid">
          <div *ngIf="fc.companyName.hasError(''required'')">
            <div>
              Company Name is required!
            </div>
          </div>
          <div *ngIf="fc.companyName.hasError(''minlength'')">
            <div>
              Company Name cannot be less than 3 characters!
            </div>
          </div>
          <div *ngIf="fc.companyName.hasError(''maxlength'')">
            <div>
              Company Name cannot be more than 100 characters!
            </div>
          </div>
        </div>
      </div>
      <div>
        <button mat-raised-button color="primary" matStepperNext [disabled]="companyForm.status != ''VALID''">Next</button>
      </div>
    </form>
  </mat-step>
  <mat-step [stepControl]="idForm">
    <form [formGroup]="idForm">
      <ng-template matStepLabel>Company ID</ng-template>
      <div>
        <div>
          <label for="registration_number">Registration Number:<span>*</span></label>
          <input type="text" formControlName="registrationNumber" placeholder="Registration Number"required/>
        </div>
        <div *ngIf="fi.registrationNumber.touched && fi.registrationNumber.invalid">
          <div *ngIf="fi.registrationNumber.hasError(''required'')">
            <div>
              Company Reg. No. is required!
            </div>
          </div>
          <div *ngIf="fi.registrationNumber.hasError(''maxlength'')">
            <div>
              Company Reg. No. cannot be more than 100 characters!
            </div>
          </div>
        </div>
      </div>
      <div>
        <button mat-raised-button color="black" matStepperPrevIoUs>Back</button> &nbsp;
        <button mat-raised-button color="success" [disabled]="isLoading" type="submit" (click)="onSubmit()">
                            <span *ngIf="isLoading"></span>
                              Submit
                          </button> &nbsp;
        <button mat-raised-button color="warn" (click)="stepper.reset()">Reset</button>
      </div>
  </mat-step>
</mat-horizontal-stepper>

this.files.name 是更改时 company_logo 的名称。

当我提交表单时,我收到了这两 (2) 个错误:

  1. core.js:6456 错误类型错误:无法在“FormData”上执行“append”:参数 2 不是“Blob”类型。
  1. 错误类型错误:无法读取未定义的属性“名称”

它指向:

formData.append("company_logo",this.files.name);

我正在尝试使用徽标上传来注册用户。我已经解决了很长时间没有任何解决方案。

我该如何解决这个问题?

或者有什么更好的方法吗?

尤其是第一个错误。

谢谢

解决方法

在您发布的代码中,您没有在任何地方为 this.files 设置值。由于错误指出字段 this.files 仍然是 undefined,因此当它尝试访问 this.files.name 时,它报告错误,在 undefined 上找不到任何字段名称。

解决方案:为 this.files 设置一个值并确保它也包含一个字段 name

React/MaterialUI - 类型错误:无法读取未定义的属性“地图”

React/MaterialUI - 类型错误:无法读取未定义的属性“地图”

data.stock_list 在第一次渲染时未定义,因为您将其初始化为 []。你可以改成

    const [data,setData] = useState(); 
    ...
    {
      data?.stock_list?.map(value => <ListItem role="listitem">{value}</ListItem>)
    }

这样它就不会继续,除非定义了 data.stock_list。

× 类型错误:无法读取 null 的属性“map”

× 类型错误:无法读取 null 的属性“map”

如何解决× 类型错误:无法读取 null 的属性“map”?

我一直在尝试使用 componentDidMount 将后端 API 与 react 连接,但是当我在 componentDidMount 中执行 console.log 时,它没有被调用,这意味着它没有触发后端 API 似乎运行良好。

class Products extends React.Component{
  constructor()
  {
    super()
    this.state={
      productsdetails:null
    }
    
  }
  componentDidMount()

  {   
    fetch(''/api/v1/products'') 
        .then((response) => response.json())
        .then((productsdetails) => this.setState({productsdetails:productsdetails }))
  }
  render(){
      console.log(this.state.productsdetails)
    return (
      <div className="body">
        <div className="container">
          {this.state.productsdetails.map((obj) => (
            <Product {...obj} />
          ))}
          
        </div>
      </div>
    )
  }
}
export default Products;

解决方法

您可以只提供有效的初始状态。问题是 this.state.productsdetails 在初始渲染和所有后续渲染中为 null,直到它被 GET 请求和响应更新。

class Products extends React.Component{
  constructor() {
    super()
    this.state={
      productsdetails: [] // <-- empty array is mappable!
    }
  }

  componentDidMount() {   
    fetch(''/api/v1/products'') 
      .then((response) => response.json())
      .then((productsdetails) => {
        this.setState({ productsdetails })
      });
  }

  render() {
    return (
      <div className="body">
        <div className="container">
          {this.state.productsdetails.map((obj) => (
            <Product {...obj} />
          ))}
        </div>
      </div>
    )
  }
}

或者使用条件渲染来渲染其他内容,直到填充状态。在这里,我不渲染任何内容 (null),直到 productsdetails 状态为真。

class Products extends React.Component{
  constructor() {
    super()
    this.state={
      productsdetails: null
    }
  }

  componentDidMount() {   
    fetch(''/api/v1/products'') 
      .then((response) => response.json())
      .then((productsdetails) => {
        this.setState({ productsdetails })
      });
  }

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

    if (!productsdetails) return null;

    return (
      <div className="body">
        <div className="container">
          {this.state.productsdetails.map((obj) => (
            <Product {...obj} />
          ))}
        </div>
      </div>
    )
  }
}

“类型错误:无法读取未定义的属性‘过滤器’”以及类似的其他数组函数,如使用 ReactJS 和 redux 的 map

“类型错误:无法读取未定义的属性‘过滤器’”以及类似的其他数组函数,如使用 ReactJS 和 redux 的 map

如何解决“类型错误:无法读取未定义的属性‘过滤器’”以及类似的其他数组函数,如使用 ReactJS 和 redux 的 map?

我正在学习教程,但此时我卡住了。当我尝试过滤 Product 数组时,它给了我 TypeError: Cannot read property ''filter'' of undefined。我根据教程使用 Axios 实现了相同的功能,并且它正在工作。然后讲师更改为 redux,我按照相同的步骤操作,这就是我收到错误的时候。我是 React 的新手,也是 Axios 和 Redux 的新手,我一直在试图找出问题所在,但一无所获。

这是我的 ProductScreens.jsx 发生错误的地方:

import React,{ useEffect } from "react";
import rating from "../Components/rating.jsx";
import { usedispatch,useSelector } from "react-redux";
import { listProducts } from "../actions/productActions.js"

function Sale({product}){
        if("salePrice" in product){
                return <li>Sale Price: ₹{product.salePrice}</li>;
        }
        else
            return null;
    }
export default function ProductsScreen(props){
        const dispatch = usedispatch();
        const productList = useSelector( state => state.productList);
        const {loading,error,products} = productList;
        useEffect(() =>{
                dispatch(listProducts());
        },[dispatch]);
        const product = products.filter(prod => prod.category === props.match.params.category && prod.subcategory === props.match.params.subcategory);
        return (
        <div className="container-fluid main-cards">
                <div className="row">
                {
                    product.map(product => (
                        <div key={product._id} className="col-12 col-md-6 col-lg-4 main-card-item">
                            <div className="card">
                                <a href={`/product/${product._id}`}><img src={product.mainImage} className="card-img-top" alt="..."></img></a>
                                <div className="card-body product-card list-group">
                                    <h5 className="card-title">{product.name}</h5>
                                    <p className="card-text">{product.description}</p>
                                    <ul className="list-unstyled mt-3 mb-4">
                                            <li>Price: ₹{product.price}</li>
                                            <Sale  product={product}/>
                                            <li><a href="#" className="card-link">Buy Now</a></li>
                                            <li>
                                                <rating rating={product.rating} numReview={product.numReview}/>
                                            </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    ))};
                
                </div>
        </div>
    )
}

这是我的 productActions.js

import Axios from "axios";
import { PRODUCT_LIST_REQUEST,PRODUCT_LIST_SUCCESS,PRODUCT_LIST_FAIL } from "../constants/productConstants"

export const listProducts = () => async (dispatch) =>{
    dispatch({
        type: PRODUCT_LIST_REQUEST,});
    try {
        const {data} = await Axios.get(''/api/products'');
        dispatch({type: PRODUCT_LIST_SUCCESS,payload : data});
    }catch(error){
        dispatch({type: PRODUCT_LIST_FAIL,payload: error.message});
    }
}

这是我的 productReducers.js


export const productListReducer = (state = {loading: true,products: [] },action) =>{
    switch(action.type){
        case PRODUCT_LIST_REQUEST :
            return {loading: true};
        case PRODUCT_LIST_SUCCESS:
            return {loading: false,products: action.payload};
        case PRODUCT_LIST_FAIL :
            return {loading: false,error: action.payload};
        default:
            return state;
    }
}

还有我的 productConstants.js

export const PRODUCT_LIST_REQUEST = "PRODUCT_LIST_REQUEST";
export const PRODUCT_LIST_SUCCESS = "PRODUCT_LIST_SUCCESS";
export const PRODUCT_LIST_FAIL = "PRODUCT_LIST_FAIL";

我已经尝试解决它,但我无法找出问题所在。我在 ProductScreens.jsx 中做了 console.log(products) 而不是 const product = products.filter(prod => prod.category === props.match.params.category && prod.subcategory === props.match.params.subcategory); 并且还用 return 替换了 <h1></h1> 的内容并得到了以下对象:

[
    {
        "_id": "1","name": "example1","category": "example category1","subcategory": "example subcategory1","image": [
            {
                "_id": "image1","name": "/images/example1.jpg"
            }
        ],"mainImage": "/images/example1.jpg","price": "19000","brand": "brand1","rating": 4.5,"numReview": 10,"description": "some description for example1."
    },{
        "_id": "2","name": "example2","image": [
            {
                "_id": "image2","name": "/images/example2.jpg"
            }
        ],"mainImage": "/images/example2.jpg","price": "16791","salePrice": "15500","brand": "brand2","rating": 4.7,"description": "some description for example2."
    },{
        "_id": "3","name": "example","category": "example category2","subcategory": "example subcategory3","image": [
            {
                "_id": "image3","name": "/images/example3-1.jpg"
            },{
                "_id": "image4","name": "/images/example3-2.jpg"
            },{
                "_id": "image5","name": "/images/example3-3.jpg"
            },{
                "_id": "image6","name": "/images/example3-4.jpg"
            }
        ],"mainImage": "/images/example3-1.jpg","price": "8549","salePrice": "7200","brand": "brand3","rating": 3,"description": "some description for example3."
    },{
        "_id": "4","name": "example4","category": "example category3","subcategory": "example subcategory4","image": [
            {
                "_id": "image7","name": "/images/example4.jpg"
            }
        ],"mainImage": "/images/example4.jpg","price": "450","brand": "brand4","description": "some description for example4."
    },{
        "_id": "5","name": "example5","subcategory": "example subcategory2","image": [
            {
                "_id": "image8","name": "/images/example5.jpg"
            }
        ],"mainImage": "/images/example5.jpg","price": "30000","salePrice": "27000","brand": "brand5","description": "some description for example5"
    }
]

看看上面的对象,filter() 应该可以工作,但不是。此外,上面的对象与我使用 axios 时得到的对象相同,当时它运行良好。所以我不知道为什么它不再起作用了。 此外,当我尝试 console.log(products._id) 或任何其他属性时,我得到相同的 TypeError。我试过 console.log(products[0]) 想也许我必须这样做才能得到第一个对象,因为它是一个对象数组,我得到了 TypeError: Cannot read property ''0'' of undefined

解决方法

所以我想通了。我找到了两个解决方案。首先,结果我在 PRODUCT_LIST_SUCCESS 操作发生之前得到了两个对象。在第一个对象中,products 是初始状态的空数组,而在从 PRODUCT_LIST_REQUEST 操作接收的第二个对象中,只有一个 loading 属性,因此 {{1} } 未定义。因此,我将 productsReducers.js 中的 products 语句用于 switch case 更改为 PRODUCT_LIST_REQUEST 并且成功了。 我的第二个解决方案是检查 return {loading: true,products: []}; 是真还是假,并且仅在 loading 为假时才执行我的代码并呈现页面。 我不是一个狂热的程序员,所以我不知道最佳编程实践,但我正在使用第二种解决方案。

我们今天的关于类型错误:无法读取 React js无法读取actors.json的分享已经告一段落,感谢您的关注,如果您想了解更多关于Angular - 错误类型错误:无法读取未定义的属性“名称”、React/MaterialUI - 类型错误:无法读取未定义的属性“地图”、× 类型错误:无法读取 null 的属性“map”、“类型错误:无法读取未定义的属性‘过滤器’”以及类似的其他数组函数,如使用 ReactJS 和 redux 的 map的相关信息,请在本站查询。

本文标签:

上一篇如何在 Kotlin 中使用 moshi 解析 json 本地文件(kotlin monad)

下一篇想要从 Vuejs 中的 AXIOS GET api 调用重定向到 URL(vue获取重定向的参数)