未被捕获的TypeError:无法分配为只读对象“#<object>”的属性“

时间:2019-01-29 04:34:33

标签: reactjs babel

我不知道这段代码有什么区别。 类a是组件,示例是example.js

import React, {Component} from 'react';

const styles = {
    border: {
        display: 'inline-block',
        height: '19px',
        padding: '1px 8px 0',
        border: '2px solid',
        borderRadius: '12px',
        lineHeight: '20px',
        fontSize: '14px',
        verticalAlign: 'top',
    },
    default: {
        display: 'inline-block',
        height: '20px',
        padding: '1px 10px 0',
        borderRadius: '10px',
        lineHeight: '21px',
        fontSize: '13px',
        verticalAlign: 'top',
    },
    state: {
        display: 'inline-block',
        width: '14px',
        height: '13px',
        paddingTop: '1px',
        lineHeight: '14px',
        fontSize: '11px',
        color: '#fff',
        letterSpacing: '-0.5px',
        textAlign: 'center',
        verticalAlign: 'top',
    }
};

class A extends Component {
    static defaultProps = {
        type: 'default',
    };

    render() {
        const {
            label,
            style,
            type,
            ...other
        } = this.props;


        switch (type) {

            case 'border':
                elementStyle = styles.border;
                break;
            case 'default':
                elementStyle = styles.default;
                break;
            case 'state':
                elementStyle = styles.state;
                break;
        }

        return (
            <span style={Object.assign(elementStyle, style)} {...other}>{label}</span>
        );
    }
}

export default A;

,示例代码为example.js

import A from './A';

    export default class Example extends React.Component {
        render() {
            return (
                <div>
                    <A style={{background: '#fe6969', color: '#fff'}} /> &nbsp;
                    <A style={{background: '#ff8137', color: '#fff'}} /> &nbsp;
                    <A  style={{background: '#fcb400', color: '#fff'}} /> &nbsp;
                </div>
            );
        }
    }

此代码错误是未捕获的TypeError:无法分配为只读对象'#'的属性'background'

我使用babel-loader 8,babel7,webpack4

如果我正确,则Object.assgin({},elementStyle,style)正在工作。 我认为重新呈现A组件时会发生此错误。 我不知道为什么会出现这个错误...

请帮助我。

1 个答案:

答案 0 :(得分:2)

您需要做的就是使用传播连接/合并两个这样的对象

{{...elementStyle, ...style}}  or

{Object.assign({}, elementStyle , style) }

您应该了解Object.assign的工作原理。它返回目标对象作为其操作的返回值。

所以,在第一种语法中:

Object.assign({}, elementStyle , style)

您正在创建具有元素样式和样式的可枚举属性的全新对象

如果您这样做:

Object.assign(elementStyle, style)

然后 elementStyle本身就是目标对象,因此它将被突变,也就是从Object.assign返回的内容。

这是我的意思的例子。

示例1:

// With no new target object
const original = [{id:1}, {id:2}, {id:3}];

const newArray = original.map(elem => {
  return Object.assign(elem, {id:2});
});

console.log('Original object has changed');
console.log(original);

//------------------------------

// With a new target object
const original2 = [{id:1}, {id:2}, {id:3}];

const newArray2 = original2.map(elem => {
  return Object.assign({}, elem, {id:2});
});

console.log('Original object has not changed');
console.log(original2);

示例2:

var styles =  {
  circle: {backgroundColor: 'yellow', height: '1005', width: '100%'},
  circleA: {backgroundColor: 'blue'},
};

因此,我们需要所有圆都具有默认的cir某些圆样式,但是我们需要更改某些属性,

// background yellow
<div style={styles.circle}></div>

// background  blue
<div style={Object.assign(styles.circle, styles.circleA)}></div>

// expeted background yellow, but it's blue. cus styles.circle still have it's merged value
<div style={styles.circle}></div>

解决方案是将一个空对象传递给Object.assign()。通过这样做,您要告诉该方法使用传递的对象生成一个 NEW对象

示例3:

const obj1 = {
  name: "J"
}

const obj2 = {
  gander: "m"
}

// Here, obj1 is the same after the Object.assign call
console.log(Object.assign({}, obj1, obj2));
console.log(obj1)
console.log(obj2)

console.log("without empty obj passed")

// Note that after this call, obj1 holds both keys. So this will mutate it:
console.log(Object.assign(obj1, obj2));
console.log(obj1) // This is different now
console.log(obj2)

就您而言,

`<A propstyle={{background: '#fe6969', color: '#fff'}} />

<A propstyle={{background: '#ff8137', color: '#fff'}} /> ` 

component组件在Parent中定义了两次,这意味着我们将得到两个圆,子组件将渲染两次。

,然后在您定义的子组件中,如下所示:

<span style={Object.assign(elementStyle , style) }{...other}>{label}</span>

首次渲染:

Object.assign将属性style的属性从右到左覆盖为elementStyle,这里elementStyle本身是目标对象,这将是从Object.assign返回的内容。

风格道具:{ background: "#fe6969", color: "#fff" }

elementStyle:{ background: "#fe6969", borderRadius: "10px", color: "#fff" }

第二个渲染:

Object.assign尝试从右到左覆盖属性,但是elementStyle具有{ background: "#fe6969", borderRadius: "10px", color: "#fff" }

并且Object.assign仍在循环中(请记住示例1 .map())

风格道具:{ background: "#ff8137", color: "#fff" }

抛出错误:'TypeError:由于没有新的目标对象,在{Object.assign(elementStyle , style) }时无法分配为对象'的只读属性'background'。

请找到完整的代码here

希望有帮助。 read more

相关问题