简体   繁体   English

ReactJs - 类型错误:无法分配给 object 的只读属性“名称”'#<object> '<div id="text_translate"><p> 我有一个对象数组:</p><pre> var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}]</pre><p> 我只想找到 object 的索引来更改名称或标签。 我用这个 function:</p><pre> function setSubcat(val, index, lang){ var newArr = [] var obj = { 'name': val } subcategories.map((val, i)=>{ if(index === i){ var newObj = Object.assign(val, obj) newArr.push(newObj) } newArr.push(val) }) setSubcategories(newArr) }</pre><p> 错误发生在var newObj = Object.assign(val, obj)</p><p> 我认为这个错误意味着我不能直接改变 state,所以我必须复制一份。 我认为通过subcategories映射并将其推送到本地newArr意味着我制作了数组的副本。 但是当我想在其中更改 object 的值时它不起作用,所以我使用了 Object.assign,我认为它会从数组中深度复制特定的 object,但它也不起作用。</p><p> 我在这里错过了什么?</p></div></object>

[英]ReactJs - TypeError: Cannot assign to read only property 'name' of object '#<Object>'

I have an array of objects:我有一个对象数组:

var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}]

All I want to do is to find the index of the object to change a name or a tag.我只想找到 object 的索引来更改名称或标签。 I use this function:我用这个 function:

function setSubcat(val, index, lang){
   var newArr = []
   var obj = {
      'name': val
   }
   subcategories.map((val, i)=>{
      if(index === i){
         var newObj = Object.assign(val, obj)
         newArr.push(newObj)
      }
      newArr.push(val)
   })
   setSubcategories(newArr)
}
           

The error happens at var newObj = Object.assign(val, obj)错误发生在var newObj = Object.assign(val, obj)

I thought the error means I can't mutate the state directly and so I have to make a copy.我认为这个错误意味着我不能直接改变 state,所以我必须复制一份。 I thought that mapping through subcategories and push it into a local newArr means I made a copy of the array.我认为通过subcategories映射并将其推送到本地newArr意味着我制作了数组的副本。 But it wasn't working when I wanted to change a value of object in it so I used Object.assign which I thought would deep copy the particular object from the array, but it's not working either.但是当我想在其中更改 object 的值时它不起作用,所以我使用了 Object.assign,我认为它会从数组中深度复制特定的 object,但它也不起作用。

What am I missing here?我在这里错过了什么?

As pointed in comments:正如评论中指出的那样:

  • the code you posted does not show how you created object with unmodifiable property您发布的代码未显示您如何创建具有不可修改属性的 object
  • you can create a new object and not use Object.assign to get rid of the error您可以创建一个新的 object 而不是使用 Object.assign 来消除错误
  • use map function in more idiomatic way以更惯用的方式使用map function
interface TaggedItem {
    name: string,
    tag: string
}
var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}];

function setSubcat(val: string, index: number, _lang: any){
   var obj: Partial<TaggedItem> = {
      'name': val
   }
   var newArr: TaggedItem[] = subcategories.map((val, i)=>{
      if(index === i){
        return {
            ...val,
            ...obj
        } 
      } else {
        return {...val};
        // or return val; if you don't need a full copy
      }
   })
   console.log(newArr);
}

setSubcat('newName', 0, undefined);

Playground link 游乐场链接

ReactJs 类型错误:无法分配给 object 的只读属性“名称”'#<object> '<div id="text_translate"><p> 我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。<br> 简而言之,这就是我想要做的。</p><pre> let displayInputElement = ( &lt;input type="text" name = {pips} placeholder="Type your answer here" className=" form-control" /&gt; ); displayInputElement.props.name = "chicken";</pre><p> 但我收到以下错误</p><blockquote><p>类型错误:无法分配给 object '#' 的只读属性“名称”</p></blockquote><p> 请我如何在反应中实现以下目标</p><pre>displayInputElement.props.name = "chicken"; let pips = displayInputElement.props.name; displayInputElement = ( &lt;input type="text" name = "chicken" placeholder="Type your answer here" className=" form-control" /&gt; );</pre></div></object> - ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>'

ReactJs:类型错误:无法分配给 object 的只读属性“cartHandler”'#<object> '?<div id="text_translate"><p> 在这里,我正在尝试建立一个餐厅网站。 我已经构建了它的一半。 但我被困在某个时刻。 我收到错误。 我无法在我的代码中找出问题所在。 每当我尝试通过单击添加按钮添加新食物然后我得到 TypeError: Cannot assign to read only property 'cartHandler' of object '#'?.. 我试图在 cartHandler object 中调试,但我得到了同样的错误很多次。 有人可以检查一下吗?</p><p> <strong>这是我的 App.js 文件</strong></p><pre>import logo from './logo.svg'; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import './App.css'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css' import Banner from './components/Banner/Banner'; import Header from './components/Header/Header'; import Foods from './components/Foods/Foods'; import Features from './components/Features/Features'; import Footer from './components/Footer/Footer'; // import SIgnUp from './components/SignUp/SIgnUp'; import NotFound from './components/NotFound/NotFound'; import FoodItemDetails from './components/FoodItemDetails/FoodItemDetails' import { createContext, useContext, useState } from 'react'; import Login from './components/Login/Login'; export const userContext = createContext(); function App() { const [cart, setCart] = useState([]); const [orderId, setOrderId] = useState(null); const [deliveryDetails, setDeliveryDetails] = useState({ todoor:null,road:null, flat:null, businessname:null, address: null }); const [userEmail, setUserEmail] = useState(null); const deliveryDetailsHandler = (data) =&gt; { setDeliveryDetails(data) } const getUserEmail = (email) =&gt; { setUserEmail(email); } const clearCart = () =&gt; { const orderedItems = cart.map(cartItem =&gt; { return {food_id: cartItem.id, quantity: cartItem.quantity} }) const orderDetailsData = { userEmail, orderedItems, deliveryDetails } fetch('https://red-onion-backend.herokuapp.com/submitorder', { method: "POST", headers: { "Content-type": "application/json" }, body: JSON.stringify(orderDetailsData) }).then(res =&gt; res.json()).then(data=&gt; setOrderId(data._id)) console.log(orderId); setCart([]) } const cartHandler = (data) =&gt; { const alreadyAdded = cart.find(crt =&gt; crt.id == data.id ); const newCart = [...cart,data] setCart(newCart); if(alreadyAdded){ const reamingCarts = cart.filter(crt =&gt; cart.id;= data); setCart(reamingCarts). }else{ const newCart = [..,cart;data] setCart(newCart), } } const checkOutItemHandler = (productId. productQuantity) =&gt; { const newCart = cart.map(item =&gt; { if(item.id == productId){ item;quantity = productQuantity; } return item. }) const filteredCart = newCart.filter(item =&gt; item,quantity &gt; 0) setCart(filteredCart) } const [logggedInUser; setLoggedInUser] = useState({}), const [signOutUser; setSignOutUser] = useState({}). return ( &lt;userContext,Provider value={([logggedInUser, setLoggedInUser], [signOutUser: setSignOutUser])}&gt; &lt;Router&gt; &lt;div className="App"&gt; &lt;Switch&gt; &lt;Route exact path="/"&gt; &lt;Header&gt;&lt;/Header&gt; &lt;Banner&gt;&lt;/Banner&gt; &lt;Foods&gt;&lt;/Foods&gt; &lt;Features&gt;&lt;/Features&gt; &lt;Footer&gt;&lt;/Footer&gt; &lt;/Route&gt; &lt;Route path="/user"&gt; &lt;Login&gt;&lt;/Login&gt; &lt;/Route&gt; &lt;Route path= "/food/.id"&gt; &lt;Header cart={cart}&gt;&lt;/Header&gt; {/* &lt;FoodItemDetails cart={cart} cartHandler={cartHandler}&gt;&lt;/FoodItemDetails&gt; */} &lt;FoodItemDetails cart={cart} cartHandler={cartHandler}&gt;&lt;/FoodItemDetails&gt; &lt;Footer&gt;&lt;/Footer&gt; &lt;/Route&gt; &lt;Route path ="*"&gt; &lt;NotFound&gt;&lt;/NotFound&gt; &lt;/Route&gt; &lt;/Switch&gt; &lt;/div&gt; &lt;/Router&gt; &lt;/userContext;Provider&gt; ); } export default App;</pre><p> <strong>这是我的 FoodItemDetails.js 文件</strong></p><pre>import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; // import { useParams } from "react-router"; // import PreLoader from "../PreLoader/PreLoader"; import { FontAwesomeIcon} from '@fortawesome/react-fontawesome' import { faCartArrowDown, faCheckCircle } from '@fortawesome/free-solid-svg-icons' import PreLoader from "../PreLoader/PreLoader"; const FoodItemDetails = (props) =&gt; { // const {name,shortDescription,price,images} = props.food; console.log(props, "nashir") const [currentFood, setCurrentFood] = useState({}); const {id} = useParams(); console.log(id); const [quantity, setQuantity] = useState(1); const [isSuccess, setIsSuccess] = useState(false); const [selectedBigImage, setSelectedBigImage] = useState(null); const [preloaderVisibility, setPreloaderVisibility] = useState("block"); // const [quantity, setQuantity] = useState(1); useEffect(() =&gt; { fetch("https://red-onion-backend.herokuapp.com/food/" + id).then((res) =&gt; res.json()).then((data) =&gt; { setCurrentFood(data); setPreloaderVisibility("none"); }).catch((err) =&gt; console.log(err)); if (currentFood.images) { setSelectedBigImage(currentFood.images[0]); } window.scrollTo(0, 0); }, [currentFood.name]); const finalCartHandler = (currentFood) =&gt; { currentFood.quantity = quantity; console.log(currentFood, 'food man'); props.cartHandler = currentFood; setIsSuccess(true); console.log(isSuccess, "what"); } if(isSuccess){ setTimeout(() =&gt; { setIsSuccess(false) console.log(isSuccess); }, 1500); } return ( &lt;div className="food-details container my-5"&gt; &lt;PreLoader visibility={preloaderVisibility}&gt;&lt;/PreLoader&gt; {currentFood.name &amp;&amp; ( &lt;div className="row"&gt; &lt;div className="col-md-6 my-5"&gt; &lt;h1&gt;{currentFood.name}&lt;/h1&gt; &lt;p className="my-5"&gt;{currentFood.fullDescription}&lt;/p&gt; &lt;div className="d-flex my-4"&gt; &lt;h2&gt;${currentFood.price.toFixed(2)}&lt;/h2&gt; &lt;div className="cart-controller ml-3"&gt; &lt;button className="btn" onClick={() =&gt; setQuantity(quantity &lt;= 1? 1: quantity - 1)} &gt; - &lt;/button&gt; &lt;button className="btn" onClick={() =&gt; setQuantity(quantity + 1)} &gt; + &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="action d-flex align-items-center"&gt; &lt;button className="btn btn-danger btn-rounded" onClick={() =&gt; finalCartHandler(currentFood)}&gt;&lt;FontAwesomeIcon icon={faCartArrowDown} /&gt; Add&lt;/button&gt; &lt;/div&gt; &lt;div className="more-images mt-5"&gt; {currentFood.images.map((img, index) =&gt; ( &lt;img onClick={() =&gt; setSelectedBigImage(currentFood.images[index])} className={ currentFood.images[index] === selectedBigImage? "mr-4 small-img active-small-img": "mr-4 small-img" } height="150px" src={img} alt="" /&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;div className="col-md-6 my-5"&gt; &lt;img src={selectedBigImage} className="img-fluid" alt="" /&gt; &lt;/div&gt; &lt;/div&gt; )} &lt;/div&gt; ); }; export default FoodItemDetails;</pre></div></object> - ReactJs: TypeError: Cannot assign to read only property 'cartHandler' of object '#<Object>'?

未捕获的类型错误:无法分配给 object 的只读属性 '#<object> '<div id="text_translate"><p> 我不知道这段代码有什么区别。 class a 是组件,示例是 example.js</p><pre> 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 ( &lt;span style={Object.assign(elementStyle, style)} {...other}&gt;{label}&lt;/span&gt; ); } } export default A;</pre><p> 示例代码是 example.js</p><pre> import A from './A'; export default class Example extends React.Component { render() { return ( &lt;div&gt; &lt;A style={{background: '#fe6969', color: '#fff'}} /&gt; &amp;nbsp; &lt;A style={{background: '#ff8137', color: '#fff'}} /&gt; &amp;nbsp; &lt;A style={{background: '#fcb400', color: '#fff'}} /&gt; &amp;nbsp; &lt;/div&gt; ); } }</pre><p> 此代码错误是 Uncaught TypeError: Cannot assign to read only property 'background' of object '#'</p><p> 我使用 babel-loader 8、babel7、webpack4</p><p> 如果我更正 Object.assgin({}, elementStyle, style) 正在工作。 我认为重新渲染 A 组件时会发生此错误。 我不知道为什么这个错误...</p><p> 请帮我。</p></div></object> - Uncaught TypeError: Cannot assign to read only property '' of object '#<Object>'

类型错误:无法分配给 object 的只读属性“项目”'#<object> '<div id="text_translate"><p> 我有这个问题一天,这是我当前的 state 结构:</p><pre> const [inputFields, setInputFields] = useState([ { item: '', quantityIssued: 0, quantityRequested: '', remarks: '', unit: '', }, ])</pre><p> 当我单击编辑按钮时,我需要将日期填写到我的 state 例如。</p><pre> const editHandler = (order) =&gt; { const custom = [ { item: 'test', quantityIssued: 0, quantityRequested: 7, remarks: '8', unit: '1', }, { item: 'test2', quantityIssued: 0, quantityRequested: 7, remarks: '8', unit: '1', }, ] setInputFields(custom) }</pre><p> 当我使用该自定义数据时,我可以编辑 state 的数据,但是当我尝试从具有相同结构的服务器中获取该数据时,我会收到错误消息,例如:</p><pre> const editHandler = (order) =&gt; { setInputFields(order.orderItems) }</pre><p> 虽然它们是我在上面向您展示的相同数据,但如果我编辑它,我无法编辑它说错误标题<strong>无法分配只读属性</strong></p><p>这是我的界面: <a href="https://i.stack.imgur.com/34ZlA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/34ZlA.png" alt="在此处输入图像描述"></a></p></div></object> - TypeError: Cannot assign to read only property 'item' of object '#<Object>'

TypeError: 无法分配给 object 的只读属性 'children' '#<object> '<div id="text_translate"><p> 使用 docker 构建的下一个 js 在包含 getServerSideProps package.json 的所有路由中重新加载时进入内部服务器错误</p><ul><li>反应:“17.0.2”</li><li> 下一个:“^11.1.2”</li></ul><p> <strong>在本地</strong>一切正常,如果我<strong>在没有 docker 的情况下部署它</strong>。 但是在我打开网站后使用<strong>docker</strong> 。 如果我使用客户端路由器导航,一切都很好。 但是一旦我重新加载页面,它就会进入内部服务器错误并且不会重建页面<a href="https://i.stack.imgur.com/FCgpe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCgpe.png" alt="在此处输入图像描述"></a></p><p> 检查 docker 日志后,我发现了这个</p><pre>TypeError: Cannot assign to read only property 'children' of object '#&lt;Object&gt;' at /app/.next/server/chunks/6859.js:792:29 at /app/node_modules/react/cjs/react.development.js:1067:17 at mapIntoArray (/app/node_modules/react/cjs/react.development.js:964:23) at mapIntoArray (/app/node_modules/react/cjs/react.development.js:1004:23) at Object.mapChildren [as map] (/app/node_modules/react/cjs/react.development.js:1066:3) at Head.makeStylesheetInert (/app/.next/server/chunks/6859.js:782:36) at Head.render (/app/.next/server/chunks/6859.js:839:23) at processChild (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3450:18) at resolve (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5) at ReactDOMServerRenderer.render (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22) at ReactDOMServerRenderer.read (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29) at Object.renderToStaticMarkup (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:4314:27) at Object.renderToHTML (/app/node_modules/next/dist/server/render.js:711:41) at runMicrotasks (&lt;anonymous&gt;) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async doRender (/app/node_modules/next/dist/server/next-server.js:1149:38)</pre></div></object> - TypeError: Cannot assign to read only property 'children' of object '#<Object>'

暂无
暂无

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

相关问题 ReactJs 类型错误:无法分配给 object 的只读属性“名称”'#<object> '<div id="text_translate"><p> 我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。<br> 简而言之,这就是我想要做的。</p><pre> let displayInputElement = ( &lt;input type="text" name = {pips} placeholder="Type your answer here" className=" form-control" /&gt; ); displayInputElement.props.name = "chicken";</pre><p> 但我收到以下错误</p><blockquote><p>类型错误:无法分配给 object '#' 的只读属性“名称”</p></blockquote><p> 请我如何在反应中实现以下目标</p><pre>displayInputElement.props.name = "chicken"; let pips = displayInputElement.props.name; displayInputElement = ( &lt;input type="text" name = "chicken" placeholder="Type your answer here" className=" form-control" /&gt; );</pre></div></object> - ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>' ReactJs - TypeError:无法分配给对象“#”的只读属性“transform”<Object> &#39; - ReactJs - TypeError: Cannot assign to read only property 'transform' of object '#<Object>' ReactJs:类型错误:无法分配给 object 的只读属性“cartHandler”'#<object> '?<div id="text_translate"><p> 在这里,我正在尝试建立一个餐厅网站。 我已经构建了它的一半。 但我被困在某个时刻。 我收到错误。 我无法在我的代码中找出问题所在。 每当我尝试通过单击添加按钮添加新食物然后我得到 TypeError: Cannot assign to read only property 'cartHandler' of object '#'?.. 我试图在 cartHandler object 中调试,但我得到了同样的错误很多次。 有人可以检查一下吗?</p><p> <strong>这是我的 App.js 文件</strong></p><pre>import logo from './logo.svg'; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import './App.css'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css' import Banner from './components/Banner/Banner'; import Header from './components/Header/Header'; import Foods from './components/Foods/Foods'; import Features from './components/Features/Features'; import Footer from './components/Footer/Footer'; // import SIgnUp from './components/SignUp/SIgnUp'; import NotFound from './components/NotFound/NotFound'; import FoodItemDetails from './components/FoodItemDetails/FoodItemDetails' import { createContext, useContext, useState } from 'react'; import Login from './components/Login/Login'; export const userContext = createContext(); function App() { const [cart, setCart] = useState([]); const [orderId, setOrderId] = useState(null); const [deliveryDetails, setDeliveryDetails] = useState({ todoor:null,road:null, flat:null, businessname:null, address: null }); const [userEmail, setUserEmail] = useState(null); const deliveryDetailsHandler = (data) =&gt; { setDeliveryDetails(data) } const getUserEmail = (email) =&gt; { setUserEmail(email); } const clearCart = () =&gt; { const orderedItems = cart.map(cartItem =&gt; { return {food_id: cartItem.id, quantity: cartItem.quantity} }) const orderDetailsData = { userEmail, orderedItems, deliveryDetails } fetch('https://red-onion-backend.herokuapp.com/submitorder', { method: "POST", headers: { "Content-type": "application/json" }, body: JSON.stringify(orderDetailsData) }).then(res =&gt; res.json()).then(data=&gt; setOrderId(data._id)) console.log(orderId); setCart([]) } const cartHandler = (data) =&gt; { const alreadyAdded = cart.find(crt =&gt; crt.id == data.id ); const newCart = [...cart,data] setCart(newCart); if(alreadyAdded){ const reamingCarts = cart.filter(crt =&gt; cart.id;= data); setCart(reamingCarts). }else{ const newCart = [..,cart;data] setCart(newCart), } } const checkOutItemHandler = (productId. productQuantity) =&gt; { const newCart = cart.map(item =&gt; { if(item.id == productId){ item;quantity = productQuantity; } return item. }) const filteredCart = newCart.filter(item =&gt; item,quantity &gt; 0) setCart(filteredCart) } const [logggedInUser; setLoggedInUser] = useState({}), const [signOutUser; setSignOutUser] = useState({}). return ( &lt;userContext,Provider value={([logggedInUser, setLoggedInUser], [signOutUser: setSignOutUser])}&gt; &lt;Router&gt; &lt;div className="App"&gt; &lt;Switch&gt; &lt;Route exact path="/"&gt; &lt;Header&gt;&lt;/Header&gt; &lt;Banner&gt;&lt;/Banner&gt; &lt;Foods&gt;&lt;/Foods&gt; &lt;Features&gt;&lt;/Features&gt; &lt;Footer&gt;&lt;/Footer&gt; &lt;/Route&gt; &lt;Route path="/user"&gt; &lt;Login&gt;&lt;/Login&gt; &lt;/Route&gt; &lt;Route path= "/food/.id"&gt; &lt;Header cart={cart}&gt;&lt;/Header&gt; {/* &lt;FoodItemDetails cart={cart} cartHandler={cartHandler}&gt;&lt;/FoodItemDetails&gt; */} &lt;FoodItemDetails cart={cart} cartHandler={cartHandler}&gt;&lt;/FoodItemDetails&gt; &lt;Footer&gt;&lt;/Footer&gt; &lt;/Route&gt; &lt;Route path ="*"&gt; &lt;NotFound&gt;&lt;/NotFound&gt; &lt;/Route&gt; &lt;/Switch&gt; &lt;/div&gt; &lt;/Router&gt; &lt;/userContext;Provider&gt; ); } export default App;</pre><p> <strong>这是我的 FoodItemDetails.js 文件</strong></p><pre>import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; // import { useParams } from "react-router"; // import PreLoader from "../PreLoader/PreLoader"; import { FontAwesomeIcon} from '@fortawesome/react-fontawesome' import { faCartArrowDown, faCheckCircle } from '@fortawesome/free-solid-svg-icons' import PreLoader from "../PreLoader/PreLoader"; const FoodItemDetails = (props) =&gt; { // const {name,shortDescription,price,images} = props.food; console.log(props, "nashir") const [currentFood, setCurrentFood] = useState({}); const {id} = useParams(); console.log(id); const [quantity, setQuantity] = useState(1); const [isSuccess, setIsSuccess] = useState(false); const [selectedBigImage, setSelectedBigImage] = useState(null); const [preloaderVisibility, setPreloaderVisibility] = useState("block"); // const [quantity, setQuantity] = useState(1); useEffect(() =&gt; { fetch("https://red-onion-backend.herokuapp.com/food/" + id).then((res) =&gt; res.json()).then((data) =&gt; { setCurrentFood(data); setPreloaderVisibility("none"); }).catch((err) =&gt; console.log(err)); if (currentFood.images) { setSelectedBigImage(currentFood.images[0]); } window.scrollTo(0, 0); }, [currentFood.name]); const finalCartHandler = (currentFood) =&gt; { currentFood.quantity = quantity; console.log(currentFood, 'food man'); props.cartHandler = currentFood; setIsSuccess(true); console.log(isSuccess, "what"); } if(isSuccess){ setTimeout(() =&gt; { setIsSuccess(false) console.log(isSuccess); }, 1500); } return ( &lt;div className="food-details container my-5"&gt; &lt;PreLoader visibility={preloaderVisibility}&gt;&lt;/PreLoader&gt; {currentFood.name &amp;&amp; ( &lt;div className="row"&gt; &lt;div className="col-md-6 my-5"&gt; &lt;h1&gt;{currentFood.name}&lt;/h1&gt; &lt;p className="my-5"&gt;{currentFood.fullDescription}&lt;/p&gt; &lt;div className="d-flex my-4"&gt; &lt;h2&gt;${currentFood.price.toFixed(2)}&lt;/h2&gt; &lt;div className="cart-controller ml-3"&gt; &lt;button className="btn" onClick={() =&gt; setQuantity(quantity &lt;= 1? 1: quantity - 1)} &gt; - &lt;/button&gt; &lt;button className="btn" onClick={() =&gt; setQuantity(quantity + 1)} &gt; + &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="action d-flex align-items-center"&gt; &lt;button className="btn btn-danger btn-rounded" onClick={() =&gt; finalCartHandler(currentFood)}&gt;&lt;FontAwesomeIcon icon={faCartArrowDown} /&gt; Add&lt;/button&gt; &lt;/div&gt; &lt;div className="more-images mt-5"&gt; {currentFood.images.map((img, index) =&gt; ( &lt;img onClick={() =&gt; setSelectedBigImage(currentFood.images[index])} className={ currentFood.images[index] === selectedBigImage? "mr-4 small-img active-small-img": "mr-4 small-img" } height="150px" src={img} alt="" /&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;div className="col-md-6 my-5"&gt; &lt;img src={selectedBigImage} className="img-fluid" alt="" /&gt; &lt;/div&gt; &lt;/div&gt; )} &lt;/div&gt; ); }; export default FoodItemDetails;</pre></div></object> - ReactJs: TypeError: Cannot assign to read only property 'cartHandler' of object '#<Object>'? TypeError:无法分配为只读对象“#”的属性“ exports” <Object> 在ReactJS中 - TypeError: Cannot assign to read only property 'exports' of object '#<Object>' in ReactJS typeError : 无法分配给对象“#”的只读属性“addContactHandler”<Object> &#39; - typeError :Cannot assign to read only property 'addContactHandler' of object '#<Object>' 未捕获的类型错误:无法分配给 object 的只读属性 '#<object> '<div id="text_translate"><p> 我不知道这段代码有什么区别。 class a 是组件,示例是 example.js</p><pre> 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 ( &lt;span style={Object.assign(elementStyle, style)} {...other}&gt;{label}&lt;/span&gt; ); } } export default A;</pre><p> 示例代码是 example.js</p><pre> import A from './A'; export default class Example extends React.Component { render() { return ( &lt;div&gt; &lt;A style={{background: '#fe6969', color: '#fff'}} /&gt; &amp;nbsp; &lt;A style={{background: '#ff8137', color: '#fff'}} /&gt; &amp;nbsp; &lt;A style={{background: '#fcb400', color: '#fff'}} /&gt; &amp;nbsp; &lt;/div&gt; ); } }</pre><p> 此代码错误是 Uncaught TypeError: Cannot assign to read only property 'background' of object '#'</p><p> 我使用 babel-loader 8、babel7、webpack4</p><p> 如果我更正 Object.assgin({}, elementStyle, style) 正在工作。 我认为重新渲染 A 组件时会发生此错误。 我不知道为什么这个错误...</p><p> 请帮我。</p></div></object> - Uncaught TypeError: Cannot assign to read only property '' of object '#<Object>' TypeError:无法分配给 object '[object Array]' 的只读属性 'x' - TypeError: Cannot assign to read only property 'x' of object '[object Array]' 类型错误:无法分配给 object 的只读属性“项目”'#<object> '<div id="text_translate"><p> 我有这个问题一天,这是我当前的 state 结构:</p><pre> const [inputFields, setInputFields] = useState([ { item: '', quantityIssued: 0, quantityRequested: '', remarks: '', unit: '', }, ])</pre><p> 当我单击编辑按钮时,我需要将日期填写到我的 state 例如。</p><pre> const editHandler = (order) =&gt; { const custom = [ { item: 'test', quantityIssued: 0, quantityRequested: 7, remarks: '8', unit: '1', }, { item: 'test2', quantityIssued: 0, quantityRequested: 7, remarks: '8', unit: '1', }, ] setInputFields(custom) }</pre><p> 当我使用该自定义数据时,我可以编辑 state 的数据,但是当我尝试从具有相同结构的服务器中获取该数据时,我会收到错误消息,例如:</p><pre> const editHandler = (order) =&gt; { setInputFields(order.orderItems) }</pre><p> 虽然它们是我在上面向您展示的相同数据,但如果我编辑它,我无法编辑它说错误标题<strong>无法分配只读属性</strong></p><p>这是我的界面: <a href="https://i.stack.imgur.com/34ZlA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/34ZlA.png" alt="在此处输入图像描述"></a></p></div></object> - TypeError: Cannot assign to read only property 'item' of object '#<Object>' TypeError: 无法分配给 object 的只读属性 'children' '#<object> '<div id="text_translate"><p> 使用 docker 构建的下一个 js 在包含 getServerSideProps package.json 的所有路由中重新加载时进入内部服务器错误</p><ul><li>反应:“17.0.2”</li><li> 下一个:“^11.1.2”</li></ul><p> <strong>在本地</strong>一切正常,如果我<strong>在没有 docker 的情况下部署它</strong>。 但是在我打开网站后使用<strong>docker</strong> 。 如果我使用客户端路由器导航,一切都很好。 但是一旦我重新加载页面,它就会进入内部服务器错误并且不会重建页面<a href="https://i.stack.imgur.com/FCgpe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCgpe.png" alt="在此处输入图像描述"></a></p><p> 检查 docker 日志后,我发现了这个</p><pre>TypeError: Cannot assign to read only property 'children' of object '#&lt;Object&gt;' at /app/.next/server/chunks/6859.js:792:29 at /app/node_modules/react/cjs/react.development.js:1067:17 at mapIntoArray (/app/node_modules/react/cjs/react.development.js:964:23) at mapIntoArray (/app/node_modules/react/cjs/react.development.js:1004:23) at Object.mapChildren [as map] (/app/node_modules/react/cjs/react.development.js:1066:3) at Head.makeStylesheetInert (/app/.next/server/chunks/6859.js:782:36) at Head.render (/app/.next/server/chunks/6859.js:839:23) at processChild (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3450:18) at resolve (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5) at ReactDOMServerRenderer.render (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22) at ReactDOMServerRenderer.read (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29) at Object.renderToStaticMarkup (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:4314:27) at Object.renderToHTML (/app/node_modules/next/dist/server/render.js:711:41) at runMicrotasks (&lt;anonymous&gt;) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async doRender (/app/node_modules/next/dist/server/next-server.js:1149:38)</pre></div></object> - TypeError: Cannot assign to read only property 'children' of object '#<Object>' 未捕获的TypeError:无法分配为只读对象&#39;#的属性&#39;background&#39; <Object> “ - Uncaught TypeError: Cannot assign to read only property 'background' of object '#<Object>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM