无法分配给只读属性

无法分配给只读属性

本文介绍了React Hooks:无法分配给只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新用 React.createElement() 创建的对象.我要更新的属性是 particleCopy.props.style.top.下面是我的代码.

import React, { useState } from 'react';导入'./Particles.scss';导出默认函数粒子(){constparticleStyle = { color: 'blue', position: 'absolute', top: '0px' };const [粒子,setParticle] = useState(React.createElement('div', { style:particleStyle }, '*'));const moveParticleDown = (particle, top) =>{constparticleCopy = Object.assign({},particle);particleCopy.props.style.top = top + 'px';设置粒子(粒子复制);};返回 (<div className="particles_container"><div className="particles">{particle}</div><div className="控件"><button onClick={() =>moveParticleDown(particle, 10)}>down

);}

我收到以下错误

未捕获的类型错误:无法分配给对象#"的只读属性top"

解决方案

您的 particleCopy 函数只是创建了 particle 的浅拷贝,这意味着您正在尝试变异particle 指向的对象.你可以查看一个深度克隆库,或者,现在在 React 中看起来更惯用的方法,尽可能地将对象向下传播:

constparticleCopy = {...粒子,道具: {...particle.props,风格: {...particle.props.style,顶部:顶部 + 'px'}}}设置粒子(粒子复制);

I am trying to update an object created with React.createElement(). The property I am trying to update is particleCopy.props.style.top. Below is my code.

import React, { useState } from 'react';
import './Particles.scss';

export default function Particles() {
  const particleStyle = { color: 'blue', position: 'absolute', top: '0px' };
  const [particle, setParticle] = useState(
    React.createElement('div', { style: particleStyle }, '*')
  );

  const moveParticleDown = (particle, top) => {
    const particleCopy = Object.assign({}, particle);
    particleCopy.props.style.top = top + 'px';
    setParticle(particleCopy);
  };

  return (
    <div className="particles_container">
      <div className="particles">{particle}</div>
      <div className="controls">
        <button onClick={() => moveParticleDown(particle, 10)}>down</button>
      </div>
    </div>
  );
}

I am getting the following error

Uncaught TypeError: Cannot assign to read only property 'top' of object '#<Object>'

解决方案

Your particleCopy function is only creating a shallow copy of particle, meaning you're trying to mutate the object particle is pointing to. You can either look into a deep cloning library or, what seems more idiomatic in React these days, to spread the object down as far as you have to:

const particleCopy = {
  ...particle,
  props: {
    ...particle.props,
    style: {
      ...particle.props.style,
      top: top + 'px'
    }
  }
}
setParticle(particleCopy);

这篇关于React Hooks:无法分配给只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:33