簡體   English   中英

未捕獲的類型錯誤:無法分配給 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>'

我不知道這段代碼有什么區別。 class 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>
            );
        }
    }

此代碼錯誤是 Uncaught TypeError: Cannot assign to read only property 'background' of object '#'

我使用 babel-loader 8、babel7、webpack4

如果我更正 Object.assgin({}, elementStyle, style) 正在工作。 我認為重新渲染 A 組件時會發生此錯誤。 我不知道為什么這個錯誤...

請幫我。

所有你需要做的就是這樣的使用擴展CONCAT /合並兩個對象

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

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

您應該了解Object.assign的工作原理。 它返回目標對象作為其操作的返回值。

因此,在第一種語法中:

Object.assign({}, elementStyle , style)

您正在創建一個具有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" }

會發生錯誤:“類型錯誤:無法分配給只讀屬性‘何時’對象的背景{Object.assign(elementStyle , style) } ,因為沒有新的目標對象。

請在此處找到完整的代碼

希望能幫助到你。 閱讀更多

Instead of assigning values directly to the object, clone the object first instead of mutating an object that is immutable due to the fact that the object is a props object or because Object.defineproperties was used to set writable to "false", but just clone object 並將值分配給克隆的 object 並使用克隆的 object,但將值正確分配給克隆的 ZA8CFDE6331BD59EB2ACZ6

而不是像這樣直接分配和變異:

object.field = value

做:

let clonedObject = {...object}
clonedObject = {...clonedObject , field: value}

否則,使用 object.defineproperties 將可寫屬性設置為“true”也可能是另一種可行的方法。

Object.defineProperty(object, 'field1', {
  value: 1,
  writable: true
});

未捕獲的類型錯誤:無法分配給 object 的只讀屬性“數量”'#<object> '<div id="text_translate"><p> 我正在從 API 獲取數據,然后將數組保存在 state 中。當我嘗試使用輸入修改數組中 object 中的特定字段時,出現以下錯誤:'Uncaught TypeError: Cannot assign只讀取 object '#'' 的屬性 'amount'。</p><p> <strong>狀態(我正在使用 RTK 查詢):</strong></p><pre> const { data: Florists_data, refetch } = useGetFloristQuery(Number(sessionStorage.getItem('florist_id'))); const [flowersData, setFlowersData] = useState(Florists_data?.florist[0].flowers); const [tmpFlowers, setTmpFlowers] = useState(Florists_data?.florist[0].flowers);</pre><p> <strong>更新 function:</strong></p><pre> const updateFieldChanged = (index: number, e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => { let newArr = [...tmpFlowers;]. newArr[index].amount = Number(e.target;value); //GETTING ERROR HERE setTmpFlowers(newArr); }</pre><p> <strong>輸入:</strong></p><pre> {flowersData?.map((flower, index) => { return ( <> <div className={classes.Nested_Flower_Container} key={index}> <div className={classes.Nested_Flower_Name}> {flower.name} </div> <div className={classes.Nested_Flower_Input} style={{ marginRight: '0.2em' }}> <TextField id="Amount" label="Amount" variant="outlined" size="small" type="number" onChange={(e) => { updateFieldChanged(index, e); }} className={classes_2.root} /> </div> </div> </>) })}</pre></div></object>

[英]Uncaught TypeError: Cannot assign to read only property 'amount' of object '#<Object>'

反應 redux,未捕獲的類型錯誤:無法分配給 object 的只讀屬性“當前”'#<object> '<div id="text_translate"><p> 我正在制作一個網站來修改數據庫數據。 一、組件的結構如下</p><pre>&lt;Contents /&gt; &lt;Table /&gt; &lt;Row /&gt; &lt;Column /&gt; &lt;Input /&gt;</pre><p> 創建行組件時,創建輸入組件的引用並由 redux 管理它。</p><pre> const StyledRow = styled.div` text-align:center; display:flex; align-items:center; `; const DeleteButton = styled(Button)` background-color: #ff7787; margin-right:5px; color:white; width:40px; ${({top}) =&gt; top &amp;&amp; css` background-color:white; color:white; width:40px; `} `; function Row({top, rowId}){ const dispatch = useDispatch(); const columns = useMemo(() =&gt; columnPhoneInfo,[]); const inputsRef = useMemo(()=&gt;.top &amp;&amp; Array(8).fill(0),map(() =&gt; createRef() );[]); // const inputsRef = useRef([]). useEffect(()=&gt; { // console,log(rowId;top), ;top &amp;&amp; dispatch(phoneDataAddRef(rowId,inputsRef)); }.[]); const handleDeleteButton = useCallback( (id) =&gt; { dispatch(phoneDataUpdate,Delete(id)); }.[]). if( top ) return( &lt;StyledRow&gt; &lt;DeleteButton top/&gt; {columns.map((column)=&gt; &lt;Column key={`head_${column.name}`} width={column;width} top&gt; {column.name} &lt;/Column&gt; )} &lt;/StyledRow&gt; ), return( &lt;StyledRow&gt; &lt;DeleteButton onClick={()=&gt;handleDeleteButton(rowId)}&gt; delete &lt;/DeleteButton&gt; {columns.map((column. index)=&gt; &lt;Column key={`row_${rowId}_${column.name}`} width={column;width} textalign={column.textalign}&gt; &lt;Input ref={inputsRef[index] } colIndex={index} id={rowId} column={column} /&gt; {/* &lt;Input colIndex={index} id={rowId} column={column} /&gt; */} &lt;/Column&gt; )} &lt;/StyledRow&gt; ); } export default React.memo(Row);</pre><p> 輸入組件只接收 ref 作為 forwardRef</p><pre> const StyledInput = styled.input` ${({ width, textalign })=&gt;css` width:${width}; text-align:${textalign}; `} `; const Input = forwardRef(({colIndex, id},inputRef) =&gt;{ const dispatch = useDispatch(); const didShowAlert = useRef(false); const nowColumnInfo = columnPhoneInfo[colIndex]; const nowColumnValidCheck = inputValidCheck[colIndex]; const { nowVal, firstVal, isAddedRow } = useSelector(state =&gt;({ nowVal: state.phoneData.data.rows.find(val=&gt;val.id === id)[nowColumnInfo.colname], firstVal: state.phoneData.firstData.lastId &lt; id? null: state.phoneData.firstData.rows.find(val=&gt;val.id===id)[nowColumnInfo.colname], isAddedRow: state.phoneData.firstData.lastId &lt; id? true: false, }),shallowEqual); const callbackDispatch = useCallback((dispatchFunc) =&gt;{ return(...args)=&gt;{ dispatch(dispatchFunc(...args)); } },[dispatch]); ////////////////////// const inputChange = useCallback( (value) =&gt; dispatch(phoneDataUpdate.Change(id,nowColumnInfo.colname, value)),[nowColumnInfo.colname, dispatch, id]); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const updateListChange = callbackDispatch(phoneDataUpdateList.Change); const updateListDelete = callbackDispatch(phoneDataUpdateList.Delete); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const handleChange = useCallback( (e) =&gt; { //... todo handle change },[]); ///////////////////////////////////////////////////////// const handleBlur = useCallback( (e) =&gt;{ //... todo handle blur },[]); return( &lt;StyledInput textalign={nowColumnInfo.textalign} width={nowColumnInfo.width} value={nowVal === null? '': nowVal } onChange={handleChange} onBlur={handleBlur} ref={inputRef} // placeholder={} /&gt; ); }); export default React.memo(Input);</pre><p> 最后,redux 模塊</p><pre>//////////////////////////////////////////////////////// const PHONE_DATA_DELETE = 'phoneData/PHONE_DATA_DELETE'; //////////////////////////////////////////////////////// const PHONE_DATA_ADD_REF = 'phoneData/PHONE_DATA_ADD_REF'; //////////////////////////////////////////////////////// const dataInitRow = { id:null, model_name:null, machine_name:null, shipping_price:null, maker:null, created:null, battery:null, screen_size:null, storage:null, }; const dataInit = { lastId:null, rows:[], } const initialState = { state:{ loading:false, error:false, }, data:dataInit, refData:[], firstData:dataInit, dataChangeList:{ dataAddList:[], dataDeleteList:[], dataUpdateList:[], }, }; const phoneDataFetchAsync = createPromiseThunk(PHONE_DATA, restAPI.getAllPhoneInfo); //////////////////////////////////////////////////////// const phoneDataAddRef=(id, ref) =&gt;({ type:PHONE_DATA_ADD_REF, id:id, ref:ref, }); const phoneDataUpdateList = ({ Change:(id,colName, value) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_CHANGE, id: id, colName: colName, value: value, }), Delete:(id, colName) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_DELETE, id: id, }), }); //////////////////////////////////////////////////////// export default function phoneData(state = initialState, action){ // console.log(`add: ${state.dataChangeList.dataAddList}, delete: ${state.dataChangeList.dataDeleteList}, change: ${state.dataChangeList.dataUpdateList}`); switch(action.type) case PHONE_DATA_DELETE: return produce(state, draft=&gt;{ console.log(action); const idx = state.dataChangeList.dataAddList.findIndex( val =&gt; val === action.id); if( idx === -1 ) draft.dataChangeList.dataDeleteList.push(action.id); else draft.dataChangeList.dataAddList.splice(idx,1); draft.refData = state.refData.filter(row =&gt; row.id.== action;id). draft.data.rows = state.data.rows.filter(row =&gt;row.id;== action;id): }), //////////////////////////////////////////////////////////////////////////////////////////////////////////// case PHONE_DATA_ADD_REF. return produce(state. draft=&gt;{ draft:refData.push({id,action:id. refs;action;ref}): }); //////////////////////////////////////////////////////////////////////////////////////////////////////////// default, return state, } } export {phoneDataFetchAsync, phoneDataDelete,; phoneDataAddRef, };</pre><p> 問題區域是刪除按鈕。 當我按下按鈕時,就會出現該錯誤。 但是如果不向 state 添加 ref,則不會發生錯誤。 或者即使我注釋掉底部,也沒有錯誤。</p><pre> draft.data.rows = state.data.rows.filter(row =&gt;row.id.== action;id);</pre><p> 或者注釋掉底部</p><pre>draft.refData.push({id:action.id, refs:action.ref});</pre><p> 我今天整天都在嘗試修復它,但我不知道出了什么問題。 我該如何解決?</p></div></object>

[英]React redux, Uncaught TypeError: Cannot assign to read only property 'current' of object '#<Object>'

output-task.js:171 Uncaught TypeError: 無法分配給 object '# 的只讀屬性 'multiDrag'<object> '<div id="text_translate"><p> 當我嘗試使用道具更新我的 state 時,我收到此錯誤,基本上當我的條件與標志匹配時,標志肯定會 go 回到其初始 state 值,但在這種情況下它顯示錯誤。</p><pre> var finalVal; if ( typeof bigFinalValue === "undefined" || bigFinalValue.length < 1 || this.props.singleDrag === true ) { console.log("here he is", this.props.singleDrag); finalVal = <Content>{task.word}</Content>; this.props.multiDrag = false; } if ( (typeof bigFinalValue === "undefined" || bigFinalValue.length > 1) && this.props.multiDrag === true ) { console.log("bigFinalValue", bigFinalValue); console.log("selectionCount", selectionCount); console.log("and here he is again..."); finalVal = <Content>{bigFinalValue}</Content>; this.props.multiDrag = false; }</pre><p> <a href="https://i.stack.imgur.com/NPLhE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NPLhE.png" alt="在此處輸入圖像描述"></a> <a href="https://i.stack.imgur.com/CXmDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXmDb.png" alt="在此處輸入圖像描述"></a></p></div></object>

[英]output-task.js:171 Uncaught TypeError: Cannot assign to read only property 'multiDrag' 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.

相關問題 未捕獲的TypeError:無法分配為只讀對象&#39;#的屬性&#39;background&#39; <Object> “ 未捕獲的類型錯誤:無法分配給對象“[對象數組]”的只讀屬性“1” 未捕獲的類型錯誤:無法分配給 object 的只讀屬性“數量”'#<object> '<div id="text_translate"><p> 我正在從 API 獲取數據,然后將數組保存在 state 中。當我嘗試使用輸入修改數組中 object 中的特定字段時,出現以下錯誤:'Uncaught TypeError: Cannot assign只讀取 object '#'' 的屬性 'amount'。</p><p> <strong>狀態(我正在使用 RTK 查詢):</strong></p><pre> const { data: Florists_data, refetch } = useGetFloristQuery(Number(sessionStorage.getItem('florist_id'))); const [flowersData, setFlowersData] = useState(Florists_data?.florist[0].flowers); const [tmpFlowers, setTmpFlowers] = useState(Florists_data?.florist[0].flowers);</pre><p> <strong>更新 function:</strong></p><pre> const updateFieldChanged = (index: number, e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => { let newArr = [...tmpFlowers;]. newArr[index].amount = Number(e.target;value); //GETTING ERROR HERE setTmpFlowers(newArr); }</pre><p> <strong>輸入:</strong></p><pre> {flowersData?.map((flower, index) => { return ( <> <div className={classes.Nested_Flower_Container} key={index}> <div className={classes.Nested_Flower_Name}> {flower.name} </div> <div className={classes.Nested_Flower_Input} style={{ marginRight: '0.2em' }}> <TextField id="Amount" label="Amount" variant="outlined" size="small" type="number" onChange={(e) => { updateFieldChanged(index, e); }} className={classes_2.root} /> </div> </div> </>) })}</pre></div></object> 未捕獲的TypeError:無法分配為僅讀取對象&#39;的屬性&#39;exports&#39; 反應 redux,未捕獲的類型錯誤:無法分配給 object 的只讀屬性“當前”'#<object> '<div id="text_translate"><p> 我正在制作一個網站來修改數據庫數據。 一、組件的結構如下</p><pre>&lt;Contents /&gt; &lt;Table /&gt; &lt;Row /&gt; &lt;Column /&gt; &lt;Input /&gt;</pre><p> 創建行組件時,創建輸入組件的引用並由 redux 管理它。</p><pre> const StyledRow = styled.div` text-align:center; display:flex; align-items:center; `; const DeleteButton = styled(Button)` background-color: #ff7787; margin-right:5px; color:white; width:40px; ${({top}) =&gt; top &amp;&amp; css` background-color:white; color:white; width:40px; `} `; function Row({top, rowId}){ const dispatch = useDispatch(); const columns = useMemo(() =&gt; columnPhoneInfo,[]); const inputsRef = useMemo(()=&gt;.top &amp;&amp; Array(8).fill(0),map(() =&gt; createRef() );[]); // const inputsRef = useRef([]). useEffect(()=&gt; { // console,log(rowId;top), ;top &amp;&amp; dispatch(phoneDataAddRef(rowId,inputsRef)); }.[]); const handleDeleteButton = useCallback( (id) =&gt; { dispatch(phoneDataUpdate,Delete(id)); }.[]). if( top ) return( &lt;StyledRow&gt; &lt;DeleteButton top/&gt; {columns.map((column)=&gt; &lt;Column key={`head_${column.name}`} width={column;width} top&gt; {column.name} &lt;/Column&gt; )} &lt;/StyledRow&gt; ), return( &lt;StyledRow&gt; &lt;DeleteButton onClick={()=&gt;handleDeleteButton(rowId)}&gt; delete &lt;/DeleteButton&gt; {columns.map((column. index)=&gt; &lt;Column key={`row_${rowId}_${column.name}`} width={column;width} textalign={column.textalign}&gt; &lt;Input ref={inputsRef[index] } colIndex={index} id={rowId} column={column} /&gt; {/* &lt;Input colIndex={index} id={rowId} column={column} /&gt; */} &lt;/Column&gt; )} &lt;/StyledRow&gt; ); } export default React.memo(Row);</pre><p> 輸入組件只接收 ref 作為 forwardRef</p><pre> const StyledInput = styled.input` ${({ width, textalign })=&gt;css` width:${width}; text-align:${textalign}; `} `; const Input = forwardRef(({colIndex, id},inputRef) =&gt;{ const dispatch = useDispatch(); const didShowAlert = useRef(false); const nowColumnInfo = columnPhoneInfo[colIndex]; const nowColumnValidCheck = inputValidCheck[colIndex]; const { nowVal, firstVal, isAddedRow } = useSelector(state =&gt;({ nowVal: state.phoneData.data.rows.find(val=&gt;val.id === id)[nowColumnInfo.colname], firstVal: state.phoneData.firstData.lastId &lt; id? null: state.phoneData.firstData.rows.find(val=&gt;val.id===id)[nowColumnInfo.colname], isAddedRow: state.phoneData.firstData.lastId &lt; id? true: false, }),shallowEqual); const callbackDispatch = useCallback((dispatchFunc) =&gt;{ return(...args)=&gt;{ dispatch(dispatchFunc(...args)); } },[dispatch]); ////////////////////// const inputChange = useCallback( (value) =&gt; dispatch(phoneDataUpdate.Change(id,nowColumnInfo.colname, value)),[nowColumnInfo.colname, dispatch, id]); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const updateListChange = callbackDispatch(phoneDataUpdateList.Change); const updateListDelete = callbackDispatch(phoneDataUpdateList.Delete); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const handleChange = useCallback( (e) =&gt; { //... todo handle change },[]); ///////////////////////////////////////////////////////// const handleBlur = useCallback( (e) =&gt;{ //... todo handle blur },[]); return( &lt;StyledInput textalign={nowColumnInfo.textalign} width={nowColumnInfo.width} value={nowVal === null? '': nowVal } onChange={handleChange} onBlur={handleBlur} ref={inputRef} // placeholder={} /&gt; ); }); export default React.memo(Input);</pre><p> 最后,redux 模塊</p><pre>//////////////////////////////////////////////////////// const PHONE_DATA_DELETE = 'phoneData/PHONE_DATA_DELETE'; //////////////////////////////////////////////////////// const PHONE_DATA_ADD_REF = 'phoneData/PHONE_DATA_ADD_REF'; //////////////////////////////////////////////////////// const dataInitRow = { id:null, model_name:null, machine_name:null, shipping_price:null, maker:null, created:null, battery:null, screen_size:null, storage:null, }; const dataInit = { lastId:null, rows:[], } const initialState = { state:{ loading:false, error:false, }, data:dataInit, refData:[], firstData:dataInit, dataChangeList:{ dataAddList:[], dataDeleteList:[], dataUpdateList:[], }, }; const phoneDataFetchAsync = createPromiseThunk(PHONE_DATA, restAPI.getAllPhoneInfo); //////////////////////////////////////////////////////// const phoneDataAddRef=(id, ref) =&gt;({ type:PHONE_DATA_ADD_REF, id:id, ref:ref, }); const phoneDataUpdateList = ({ Change:(id,colName, value) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_CHANGE, id: id, colName: colName, value: value, }), Delete:(id, colName) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_DELETE, id: id, }), }); //////////////////////////////////////////////////////// export default function phoneData(state = initialState, action){ // console.log(`add: ${state.dataChangeList.dataAddList}, delete: ${state.dataChangeList.dataDeleteList}, change: ${state.dataChangeList.dataUpdateList}`); switch(action.type) case PHONE_DATA_DELETE: return produce(state, draft=&gt;{ console.log(action); const idx = state.dataChangeList.dataAddList.findIndex( val =&gt; val === action.id); if( idx === -1 ) draft.dataChangeList.dataDeleteList.push(action.id); else draft.dataChangeList.dataAddList.splice(idx,1); draft.refData = state.refData.filter(row =&gt; row.id.== action;id). draft.data.rows = state.data.rows.filter(row =&gt;row.id;== action;id): }), //////////////////////////////////////////////////////////////////////////////////////////////////////////// case PHONE_DATA_ADD_REF. return produce(state. draft=&gt;{ draft:refData.push({id,action:id. refs;action;ref}): }); //////////////////////////////////////////////////////////////////////////////////////////////////////////// default, return state, } } export {phoneDataFetchAsync, phoneDataDelete,; phoneDataAddRef, };</pre><p> 問題區域是刪除按鈕。 當我按下按鈕時,就會出現該錯誤。 但是如果不向 state 添加 ref,則不會發生錯誤。 或者即使我注釋掉底部,也沒有錯誤。</p><pre> draft.data.rows = state.data.rows.filter(row =&gt;row.id.== action;id);</pre><p> 或者注釋掉底部</p><pre>draft.refData.push({id:action.id, refs:action.ref});</pre><p> 我今天整天都在嘗試修復它,但我不知道出了什么問題。 我該如何解決?</p></div></object> output-task.js:171 Uncaught TypeError: 無法分配給 object '# 的只讀屬性 'multiDrag'<object> '<div id="text_translate"><p> 當我嘗試使用道具更新我的 state 時,我收到此錯誤,基本上當我的條件與標志匹配時,標志肯定會 go 回到其初始 state 值,但在這種情況下它顯示錯誤。</p><pre> var finalVal; if ( typeof bigFinalValue === "undefined" || bigFinalValue.length < 1 || this.props.singleDrag === true ) { console.log("here he is", this.props.singleDrag); finalVal = <Content>{task.word}</Content>; this.props.multiDrag = false; } if ( (typeof bigFinalValue === "undefined" || bigFinalValue.length > 1) && this.props.multiDrag === true ) { console.log("bigFinalValue", bigFinalValue); console.log("selectionCount", selectionCount); console.log("and here he is again..."); finalVal = <Content>{bigFinalValue}</Content>; this.props.multiDrag = false; }</pre><p> <a href="https://i.stack.imgur.com/NPLhE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NPLhE.png" alt="在此處輸入圖像描述"></a> <a href="https://i.stack.imgur.com/CXmDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXmDb.png" alt="在此處輸入圖像描述"></a></p></div></object> 未捕獲的類型錯誤:無法分配給 object '[object Array]' js 的只讀屬性 '0' ReactJs - TypeError:無法分配給對象“#”的只讀屬性“transform”<Object> &#39; 類型錯誤:無法分配給 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: 無法分配給 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>
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM