1

The issue occurs when I try to upgrade React 15.X to React 16.X:

let style = {
  width:12
};
class Box extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {

    console.log(Object.getOwnPropertyDescriptor(style,'width'))

    style.width = 96;

    return (
      <div style={style}>

      </div>
    );
  }
}

outputs:

  • {value: 12, writable: true, enumerable: true, configurable: true}
  • {value: 12, writable: false, enumerable: true, configurable: false}
  • {value: 12, writable: false, enumerable: true, configurable: false}

Anyone knows why the 'writable' becomes false?

Shy
  • 47
  • 1
  • 6
  • 1
    What is `onChange`, it's not defined. And why are you trying to directly mutate a prop? I'm not sure why it changes to false after first render, but it probably shouldn't ever be writeable, it's a prop. – Jayce444 Nov 29 '19 at 02:45
  • 1
    props are Immutable, if you want to update style on air, try do this with state within componentDidMount() – Chris Chen Nov 29 '19 at 02:46
  • I edited the question. I copied the wrong code sorry – Shy Nov 29 '19 at 02:54

1 Answers1

4

Because mutating the style object is forbidden, and somewhere in the rendering process, Object.freeze(style) is called.

Ref:

Object mutation in React has long been discouraged. Object.freeze(props) is enforced back in v0.x.x days. In v16 Object.freeze(style) is added.

hackape
  • 18,643
  • 2
  • 29
  • 57