简体   繁体   English

反应TypeError:无法读取未定义的属性“替换”

[英]React TypeError: Cannot read property 'replace' of undefined

I cannot figure out why I am getting an error for a replace function inside the Render function of my component. 我无法弄清楚为什么我的组件的Render函数内部的replace函数出错。

TypeError: Cannot read property 'replace' of undefined TypeError:无法读取未定义的属性“替换”

I am simply trying to replace the string value from services.serviceImage and replace the string like "react-site/public/","" just like you would normally do on any string, I made some tests and I can confirm the value returned is a string and I made some other string replaces and it worked but in this case something is not working...why? 我只是想替换services.serviceImage中的字符串值,并像“ react-site / public /”,“”这样替换字符串就像您通常在任何字符串上一样,我做了一些测试,我可以确认返回的值是一个字符串,我用其他字符串替换了它,但它起作用了,但是在这种情况下,某些东西不起作用...为什么?

I have already tried as a regex method with no luck: 我已经尝试过没有运气的正则表达式方法:

imgUrl = imgUrl.replace("/react\-site\/public/g", "");

For some reason, my node server won't accept a replace method for the doc.serviceImage response either!!! 由于某种原因,我的节点服务器也不会接受doc.serviceImage响应的替换方法!!!!

What am I doing wrong here...? 我在这里做错了什么...?

My complete code: 我完整的代码:

import React, {Component} from 'react';
import axios from 'axios';
//import { Link } from "react-router-dom";
import './catalogue.scss';

class ServicesPage extends Component {
  state = {
    services: [],
    loading: false
  }
  componentDidMount(){

    this.setState({
      loading: true
    });

    axios.get('/services')
    .then(response => {
      console.log(response);
      this.setState({
        services: response.data.services,
        loading: false
      });
    })
    .catch( error => {
      console.log(error);
    });
    document.title = "Pain Relief and Massage Services - LA Therapy";
  }//componentDidMount

  replaceStr(str, newStr) {
   return  str = str.replace(str, newStr);
  }

  render(){

    let pageRender; 
    if(this.state.loading){
     pageRender =  <div className="pageLoader">Loading... <img src="./images/ui/spinner.svg"/></div>
    }else{
      {this.state.services.map(services => {
        let backgroundUrl = {};
        let imgUrl = services.serviceImage;

        imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

        console.log(imgUrl);


        if (services.serviceImage) {

           backgroundUrl = {
            backgroundImage: `url(${imgUrl})`,
            backgroundSize: 'cover'  
          };

        }else{
         backgroundUrl = {
            backgroundImage: 'url(./images/ui/add-image-wide.png)',
            backgroundSize: 'cover'  
          };

          pageRender =  <div className="columns white-bg">
          <div className="grid-x">
          {this.state.services.map(services =>

            <div key={services._id} className="cell large-6 medium-12 small-12 end padding-all-3x">
            <div className="catalogue-medium gray_2-border white-bg margin-distributed round-small" style={backgroundUrl}>
              <div className="dark-overlay"></div>
              <img src="./uploads/services/1538735070981-1538653957308-back-massage.jpg"/>
              <div className="tittle-bottom">{services.name} </div>
            </div>
            </div> 
            )}
          </div>
        </div>


        }

        })
      }
    }

    return(
      <div>
        {pageRender}
      </div>
    );
  }
}

export default ServicesPage;

You look to see if the property is valid AFTER you use it 您查看使用后该属性是否有效

let imgUrl = services.serviceImage;  <-- read it
imgUrl = imgUrl.replace(...)  <-- where the error occurs
if (services.serviceImage) {  <-- is truthy

So move the logic inside the check 因此,将逻辑移到检查中

let imgUrl = services.serviceImage; 
if (services.serviceImage) {  
  imgUrl = imgUrl.replace(...)

or set it to an empty string if you some reason need imgUrl outside of the if 或将其设置为空字符串(如果出于某种原因需要在if外使用imgUrl)

let imgUrl = services.serviceImage || '';
imgUrl = imgUrl.replace(...)

You might check the this.state.services first, before actually rendering them 您可能先检查this.state.services ,然后再实际渲染它们

 { this.state.services.length > 0 && this.state.services.map(services => {
        let backgroundUrl = {};
        let imgUrl = services.serviceImage;

        imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

        console.log(imgUrl);

Maybe the imageUrl is undefined initially, try for a string check whether the variable is a string. 可能一开始未定义imageUrl,请尝试输入字符串,检查变量是否为字符串。 The code goes like: 代码如下:

imgUrl = typeof imgUrl === 'string' ? imgUrl.replace("/react\-site\/public/g", "") : '';

Put you imgUrl.replace(...) inside the if (services.serviceImage) statement. imgUrl.replace(...)放在if (services.serviceImage)语句中。 In some cases services.serviceImage has an undefined value and you are getting error cuz of that. 在某些情况下, services.serviceImage具有未定义的值,并且您会得到错误提示。

...

if (services.serviceImage) {

let backgroundUrl = {};
let imgUrl = services.serviceImage;

imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

console.log(imgUrl);

backgroundUrl = {
   backgroundImage: `url(${imgUrl})`,
   backgroundSize: 'cover'  
};

}

...

You have to avoid changing state with an undefined value. 您必须避免使用未定义的值更改状态。 you are getting and undefined value and setting it to the state. 您正在获取未定义的值并将其设置为状态。 your state will get changed and renders over an undefined value. 您的状态将被更改并呈现未定义的值。 First of all, you have to check if services.serviceImage has a value then you set the value to the state. 首先,您必须检查services.serviceImage是否具有值,然后将其设置为状态。 Secondly, on you render wrap your if statement over your all code to make sure you will run your code over a true value. 其次,在渲染时,将if语句包装在所有代码上,以确保您将在真实值上运行代码。

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

相关问题 类型错误:无法读取未定义的属性“替换” - VueJS - TypeError: Cannot read property 'replace' of undefined - VueJS 错误TypeError:无法读取未定义的属性“替换” - ERROR TypeError: Cannot read property 'replace' of undefined “类型错误:无法读取未定义的属性‘替换’” - "TypeError: Cannot read property 'replace' of undefined" 节点:TypeError:无法读取未定义的属性“替换” - Node: TypeError: Cannot read property 'replace' of undefined UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“替换” - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'replace' of undefined 类型错误:无法读取 React 中未定义的属性“map” - TypeError: Cannot read property 'map' of undefined in React TypeError:无法使用React读取undefined的属性 - TypeError: Cannot read property of undefined using React 反应-未捕获的TypeError:无法读取未定义的属性“ 1” - React - Uncaught TypeError: Cannot read property '1' of undefined React Express TypeError:无法读取未定义的属性“ then” - React Express TypeError: Cannot read property 'then' of undefined 类型错误:无法读取未定义 React 的属性“任何” - TypeError: Cannot read property 'any' of undefined React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM