Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. /*
  2. When DefaultErrors is not frozen, it will be mutated. Typing 'asdf' into the first
  3. box causes the string 'the value is asdf!' to be written to DefaultErrors.foo, and
  4. any re-render of any Input component will reflect that. You can observe this by
  5. putting anything (not 'asdf') into the second box.
  6.  
  7. When it is frozen, and strict mode is off, you will never see the 'the value is asdf!'
  8. message, nor will you get any errors.
  9.  
  10. When it is frozen, and strict mode is on, you will get a:
  11. Uncaught TypeError: Cannot assign to read only property 'foo' of object ...
  12. */
  13.  
  14. const DefaultErrors = {
  15. foo: '',
  16. }
  17. //Object.freeze(DefaultErrors)
  18.  
  19. class Input extends React.Component {
  20. state = {
  21. value: '',
  22. errors: DefaultErrors
  23. }
  24.  
  25. onChange = (event) => {
  26. if (event.target.value === 'asdf') {
  27. this.setState(state => {
  28. const errors = _.extend(state.errors, { foo: 'the value is asdf!' })
  29. return { errors }
  30. })
  31. }
  32.  
  33. this.setState({
  34. value: event.target.value
  35. })
  36. }
  37.  
  38. render() {
  39. return (
  40. <p>
  41. <input
  42. onChange={this.onChange}
  43. value={this.state.value}
  44. />
  45. <span>message: {this.state.errors.foo}</span>
  46. </p>
  47. );
  48. }
  49. }
  50.  
  51. ReactDOM.render(
  52. <div>
  53. <Input />
  54. <Input />
  55. </div>,
  56. document.getElementById('root')
  57. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement